BSON 转 JSON 转换器

BSON 转 Extended JSON

关于 BSON

什么是 BSON?

BSON 是 MongoDB 使用的带长度前缀二进制文档格式。本转换器以规范 Extended JSON v2 往返处理单个 BSON 文档,并保留 ObjectId、Date、Binary、正则表达式、Timestamp、Decimal128、Int32 和 64 位 Long 值。

什么时候使用 BSON?

仅在接收方支持相同 BSON 和 Extended JSON 类型时,用于 MongoDB 文档或驱动载荷。规范 Extended JSON 并非普通 JSON:必须保留 $oid、$date、$binary、$regularExpression、$timestamp、$numberDecimal 和 $numberLong 包装器;本转换器不解码 MongoDB 线路协议消息。

JavaScript 中的 BSON

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));
				

Go 中的 BSON

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
}
				

PHP 中的 BSON

<?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