BSON to JSON Converter
About BSON
What is BSON?
BSON is MongoDB's length-prefixed binary document format. This converter round-trips one BSON document as canonical Extended JSON v2, preserving ObjectId, Date, Binary, regular expression, Timestamp, Decimal128, Int32, and 64-bit Long values.
When to use BSON?
Use BSON for MongoDB documents or driver payloads whose consumers support the same BSON and Extended JSON types. Canonical Extended JSON is not plain JSON: keep the $oid, $date, $binary, $regularExpression, $timestamp, $numberDecimal, and $numberLong wrappers; this converter does not decode MongoDB wire-protocol messages.
BSON in JavaScript
import { deserialize, EJSON, serialize } from 'bson';
const value = EJSON.deserialize({ hello: 'world' });
const bytes = serialize(value);
const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');
console.log(hex);
// Output: 160000000268656c6c6f0006000000776f726c640000
console.log(EJSON.stringify(deserialize(bytes), { relaxed: false }, 2));
BSON in Go
package main
import (
"fmt"
"go.mongodb.org/mongo-driver/bson"
)
func main() {
value := bson.D{{Key: "hello", Value: "world"}}
encoded, _ := bson.Marshal(value)
fmt.Printf("%x\n", encoded)
// Output: 160000000268656c6c6f0006000000776f726c640000
var decoded bson.M
_ = bson.Unmarshal(encoded, &decoded)
fmt.Println(decoded["hello"])
// Output: world
}
BSON in PHP
<?php
$value = ['hello' => 'world'];
$encoded = MongoDB\BSON\fromPHP($value);
echo bin2hex($encoded) . PHP_EOL;
// Output: 160000000268656c6c6f0006000000776f726c640000
$decoded = MongoDB\BSON\toPHP($encoded);
echo $decoded->hello . PHP_EOL;
// Output: world