Overview
JSON 是一种数据格式,可表示对象值、数组值、数字值、字符串值、布尔值和空值。扩展 JSON 格式定义了一组以 “ $
” 为前缀的保留键,用于表示直接对应于 BSON 中每种类型的字段类型信息,BSON 是 MongoDB 用于存储数据的格式。
扩展 JSON 格式
MongoDB扩展JSON采用不同的字符串格式来表示BSON数据。 每种不同的格式都符合JSON RFC 并满足特定的使用案例。扩展格式也称为规范格式,为每个BSON类型提供特定表示形式,可进行双向转换而不会丢失信息。 The 宽松模式格式更简洁,更接近普通JSON,但并不表示数字字段的特定位宽等所有类型信息。
请参阅下表查看每种格式的说明:
名称 | 说明 |
---|---|
扩展 | Also known as the Canonical format, this JSON representation avoids loss of
BSON type information. This format prioritizes type preservation at the loss of human-readability and
interoperability with older formats. |
宽松模式 | JSON representation that describes BSON documents with some type information loss. This format prioritizes human-readability and interoperability at the loss of
certain type information. |
要学习;了解有关JSON、 BSON和 扩展JSON的更多信息,请参阅 MongoDB Server手册中有关JSON和BSON以及扩展JSON 的文章。
扩展 JSON 示例
以下示例显示了包含以扩展JSON格式表示的 ObjectId、日期和长数字字段的文档。单击与要查看的示例格式相对应的标签页:
{ "_id": { "$oid": "573a1391f29313caabcd9637" }, "createdAt": { "$date": { "$numberLong": "1601499609" }}, "numViews": { "$numberLong": "36520312" } }
{ "_id": { "$oid": "573a1391f29313caabcd9637" }, "createdAt": { "$date": "2020-09-30T18:22:51.648Z" }, "numViews": 36520312 }
写入扩展 JSON
您可以使用 EJSON.stringify()
方法从BSON文档对象写入扩展JSON字符串。
以下示例以宽松格式输出扩展JSON字符串:
import { Code, BSON } from 'mongodb'; const EJSON = BSON.EJSON; const doc = { foo: [1, 2], bar: { hello: "world" }, code: new Code("function x() { return 1; }", {}), date: new Date(2024, 6, 20, 10, 30, 0), }; const ejsonStr = EJSON.stringify(doc); console.log(ejsonStr);
{"foo":[1,2],"bar":{"hello":"world"},"code":{"$code":"function x() { return 1; }","$scope":{}},"date":{"$date":"2024-07-20T14:30:00Z"}}
默认下,stringify()
方法返回宽松格式的扩展JSON字符串。 要指定规范格式,请将 relaxed
选项设立为 false
。
以下示例展示了如何以规范格式输出扩展JSON :
import { Code, BSON } from 'mongodb'; const EJSON = BSON.EJSON; const doc = { foo: [1, 2], bar: { hello: "world" }, code: new Code("function x() { return 1; }", {}), date: new Date(2024, 6, 20, 10, 30, 0), }; const ejsonStr = EJSON.stringify(doc, { relaxed: false }); print(ejsonStr)
{"foo":[{"$numberInt":"1"},{"$numberInt":"2"}],"bar":{"hello":"world"},"code":{"$code":"function x() { return 1; }","$scope":{}},"date":{"$date":{"$numberLong":"1721485800000"}}}
读取扩展 JSON
您可以使用 EJSON.parse()
方法将扩展JSON字符串读入该字符串描述的JavaScript值或对象中。
以下示例展示如何使用 parse()
方法将扩展JSON字符串读入JavaScript值或对象:
import { BSON } from 'mongodb'; const EJSON = BSON.EJSON; const ejsonStr = `{ "foo": [ { "$numberInt": "1" }, { "$numberInt": "2" } ], "bar": { "hello": "world" }, "code": { "$code": "function x() { return 1; }", "$scope": {} }, "bin": { "$binary": { "base64": "AQIDBA==", "subType": "00" } } }`; const doc = EJSON.parse(ejsonStr); console.log(doc);
{ foo: [ 1, 2 ], bar: { hello: 'world' }, code: new Code('function x() { return 1; }', {}), bin: Binary.createFromBase64('AQIDBA==', 0) }
注意
驾驶员将 $uuid
扩展JSON类型从字符串解析为二进制子类型 4 的 BsonBinary
对象。 有关 $uuid
字段解析的更多信息,请参阅扩展JSON规范中解析 $uuid 字段的特殊规则部分。
API 文档
要学习;了解有关本指南中讨论的任何方法或类型的更多信息,请参阅EJSON API文档。