Overview
在本指南中,您可以学习;了解在与MongoDB文档交互时如何使用扩展JSON数据格式。
JSON是一种人类可读的数据格式,用于表示对象值、数组、数字、字符串、布尔值和空值。此格式仅支持BSON数据类型的子集,而MongoDB正是使用该格式来存储数据。扩展JSON格式支持更多BSON 类型,定义了一设立以 "$
" 为前缀的保留键,用于表示直接对应于BSON中每种类型的字段类型信息。
扩展 JSON 格式
MongoDB扩展JSON采用两种字符串格式来表示BSON数据。每种格式都符合 JSON RFC 并满足特定使用案例。
下表描述了每种扩展JSON格式:
名称 | 说明 |
---|---|
规范或扩展 | A string format that avoids loss of BSON type information during data conversions. This format prioritizes type preservation at the loss of human-readability and
interoperability with older formats. |
宽松模式 | A string format 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的更多信息,请参阅JSON和BSON资源以及扩展JSON MongoDB Server手册条目。
扩展 JSON 示例
以下示例显示了一份包含 ObjectId
、日期和以扩展JSON格式表示的长数字字段的文档。选择Canonical或Relaxed Mode标签页以查看每种扩展JSON格式的示例文档:
{ "_id": { "$oid": "573a1391f29313caabcd9637" }, "createdAt": { "$date": { "$numberLong": "1601499609" }}, "numViews": { "$numberLong": "36520312" } }
{ "_id": { "$oid": "573a1391f29313caabcd9637" }, "createdAt": { "$date": "2020-09-30T18:22:51.648Z" }, "numViews": 36520312 }
写入扩展 JSON
您可以使用 toRelaxedExtendedJSON()
和 toCanonicalExtendedJSON()
方法从BSON文档对象写入扩展JSON字符串。
以下示例会输出宽松 JSON 格式和规范扩展JSON格式的BSON文档:
$doc = [ 'foo' => [1, 2], 'bar' => ['hello' => 'world'], 'code' => new MongoDB\BSON\Javascript('function x() { return 1; }', []), 'date' => new DateTime('2024-07-20 10:30:00'), ]; echo 'Relaxed format: ' , MongoDB\BSON\Document::fromPHP($doc)->toRelaxedExtendedJSON(), PHP_EOL; echo 'Canonical format: ' , MongoDB\BSON\Document::fromPHP($doc)->toCanonicalExtendedJSON(), PHP_EOL;
Relaxed format: { "foo" : [ 1, 2 ], "bar" : { "hello" : "world" }, "code" : { "$code" : "function x() { return 1; }", "$scope" : { } }, "date" : { } } Canonical format: { "foo" : [ { "$numberInt" : "1" }, { "$numberInt" : "2" } ], "bar" : { "hello" : "world" }, "code" : { "$code" : "function x() { return 1; }", "$scope" : { } }, "date" : { } }
读取扩展 JSON
您可以通过调用 json_decode()
方法将扩展JSON字符串读入PHP值,该方法将扩展JSON转换为PHP大量或对象。 将以下参数传递给 json_decode()
:
要读取的扩展JSON字符串。
布尔值,表示是否要返回大量值。如果设立为
false
,该方法将返回一个对象值。
以下示例将扩展JSON字符串值转换为PHP大量:
$ejsonStr = '{ "foo": [ { "$numberInt": "1" }, { "$numberInt": "2" } ], "bar": { "hello": "world" }, "code": { "$code": "function x() { return 1; }", "$scope": {} }, "bin": { "$binary": { "base64": "AQIDBA==", "subType": "00" } } }'; $decodedJson = json_decode($ejsonStr, true); print_r($decodedJson);
Array ( [foo] => Array ( [0] => Array ( [$numberInt] => 1 ) [1] => Array ( [$numberInt] => 2 ) ) [bar] => Array ( [hello] => world ) [code] => Array ( [$code] => function x() { return 1; } [$scope] => Array ( ) ) [bin] => Array ( [$binary] => Array ( [base64] => AQIDBA== [subType] => 00 ) ) )
API 文档
要学习;了解有关本页所讨论方法的更多信息,请参阅以下PHP扩展API文档: