JSON vs BSON Comparison

This article provides a comparison between JSON and BSON data formats, including their differences, advantages, and use cases for binary data serialization in modern applications.

Sep 24, 2022 · 2 min read · 218 Words · -Views -Comments · Digital Life
Json BSON Data Serialization 🇨🇳 阅读中文版
Read with AI

Choose an AI assistant

ChatGPT Open in a new tab with the article link and prompt
Claude Copy the prompt, then open Claude

Open Claude
Trouble reading the article?

If the prompt is missing, copy the full prompt below into your AI assistant. If the AI cannot read the article, paste the visible passage you want to discuss and add your question.

Recently while working on service integration, the other service provided data in BSON-serialized binary format. I only knew about JSON before, not BSON. Here’s a summary.

https://static.1991421.cn/2022/2022-09-25-123303.jpeg

BSON

  1. BSON is the binary version of JSON data - JSON serializes objects into strings, while BSON serializes into binary
  2. BSON supports richer data formats, such as Date/Binary types
  3. The JavaScript library for BSON processing is js-bson, which supports both browser and Node.js environments

Example

// Serialized as string
JSON.stringify({a: [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]})


// Serialized as buffer - binary data type
BSON.serialize({a: [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]})

BSON vs JSON

  1. As shown above with JSON serialization, it carries minimal metadata besides the actual data, resulting in higher space efficiency. However, BSON carries more metadata, so you’ll find that the same object takes up more space when serialized with BSON. But this isn’t absolute - in specific scenarios, BSON can actually use less space than JSON. For example:

    let now = new Date();
    let data1 = JSON.stringify({a: now});
    let data2 = BSON.serialize({a: now});
    
    console.log(Buffer.from(data1).byteLength);
    console.log(data2.byteLength);
    
  2. JSON serializes into strings, making it more human-readable. Binary data, without deserialization, cannot be understood directly.

  3. BSON carries metadata, essentially trading space for time, making traversal, querying, and modification relatively faster.

References

Authors
Developer, digital product enthusiast, tinkerer, sharer, open source lover