JSON vs BSON Comparison
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.
BSON
- BSON is the binary version of JSON data - JSON serializes objects into strings, while BSON serializes into binary
- BSON supports richer data formats, such as Date/Binary types
- 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
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);
JSON serializes into strings, making it more human-readable. Binary data, without deserialization, cannot be understood directly.
BSON carries metadata, essentially trading space for time, making traversal, querying, and modification relatively faster.