Skip to content

DOCSP-49078: Extended JSON #619

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
193 changes: 192 additions & 1 deletion source/data-formats/extended-json.txt
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,195 @@ Extended JSON
:local:
:backlinks: none
:depth: 2
:class: singlecol
:class: singlecol

.. facet::
:name: genre
:values: reference

.. meta::
:keywords: code examples, bson, relaxed, canonical, legacy

Overview
--------

JSON is a data format that represents the values of objects, arrays, numbers,
strings, booleans, and nulls. The **Extended JSON** format defines a reserved
set of keys prefixed with "``$``" to represent field type information that
directly corresponds to each type in BSON, the format that MongoDB uses to
store data.

Extended JSON Formats
---------------------

MongoDB Extended JSON features different string formats to represent BSON data.
Each of the different formats conform to the JSON RFC
and meet specific use cases. The **extended** format, also known as the
**canonical** format, features specific representations for every BSON type
for bidirectional conversion without loss of information. The **Relaxed mode**
format is more concise and closer to ordinary JSON, but does not represent
all the type information such as the specific byte size of number fields.

See the following table to see a description of each format:

.. list-table::
:header-rows: 1
:stub-columns: 1
:widths: 10 40

* - Name
- Description

* - **Extended**
- | 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.

* - **Relaxed Mode**
- | 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.

* - **Shell**
- | JSON representation that matches the syntax used in the MongoDB shell.
| This format prioritizes compatibility with the MongoDB shell, which often uses
JavaScript functions to represent types.

* - **Strict**
- | *Deprecated.* This representation is the legacy format that fully conforms to
the `JSON RFC <http://www.json.org/>`__ which allows any JSON parser to read the type information.

.. _extended_json_example_section:

.. note::

The driver parses the ``$uuid`` Extended JSON type from a string to a
``BsonBinary`` object of binary subtype 4. For more information about ``$uuid`` field
parsing, see the
:spec:`special rules for parsing $uuid fields </extended-json.rst#special-rules-for-parsing-uuid-fields>`
section in the extended JSON specification.

To learn more about JSON, BSON, and Extended JSON, see
`our article about JSON and BSON <https://www.mongodb.com/resources/basics/json-and-bson>`__
and :manual:`Extended JSON </reference/mongodb-extended-json/>` in the {+mdb-server+} manual.

Extended JSON Examples
~~~~~~~~~~~~~~~~~~~~~~

The following examples show a document containing an ObjectId, date, and long
number field represented in each Extended JSON format. Click the tab that
corresponds to the format of the example you want to see:

.. tabs::

.. tab:: Extended
:tabid: extended-format

.. code-block:: json

{
"_id": { "$oid": "573a1391f29313caabcd9637" },
"createdAt": { "$date": { "$numberLong": "1601499609" }},
"numViews": { "$numberLong": "36520312" }
}

.. tab:: Relaxed Mode
:tabid: relaxed-mode-format

.. code-block:: json

{
"_id": { "$oid": "573a1391f29313caabcd9637" },
"createdAt": { "$date": "2020-09-30T18:22:51.648Z" },
"numViews": 36520312
}

.. tab:: Shell
:tabid: shell-format

.. code-block:: json

{
"_id": ObjectId("573a1391f29313caabcd9637"),
"createdAt": ISODate("2020-09-30T18:22:51.648Z"),
"numViews": NumberLong("36520312")
}

.. tab:: Strict
:tabid: strict-format

.. code-block:: json

{
"_id": { "$oid": "573a1391f29313caabcd9637" },
"createdAt": { "$date": 1601499609 },
"numViews": { "$numberLong": "36520312" }
}

Read Extended JSON
------------------

You can read an Extended JSON documents into a {+language+} object by using the
``BsonSerializer.Deserialize<T>()`` method. The following example reads an
Extended JSON document into a ``BsonDocument`` object:

.. io-code-block::

.. input:: /includes/fundamentals/code-examples/ExtendedJson.cs
:language: csharp
:start-after: start-read-ejson
:end-before: end-read-ejson
:dedent:

.. output::
:visible: false

{ "_id" : { "$oid" : "573a1391f29313caabcd9637" }, "createdAt" : { "$date" : "1970-01-19T12:51:39.609Z" }, "numViews" : 36520312 }

Write Extended JSON
-------------------

You can write an Extended JSON string by calling the ``ToJson()`` method on a
``BsonDocument`` object or custom class. You must specify a ``JsonWriterSettings`` object
with the ``OutputMode`` property set to the desired Extended JSON format as a parameter to
the ``ToJson()`` method.

Consider the following custom class:

.. literalinclude:: /includes/fundamentals/code-examples/ExtendedJson.cs
:language: csharp
:start-after: start-custom-class
:end-before: end-custom-class

The following example outputs an instance of ``MyDocument`` in
Extended JSON format by specifying the ``CanonicalExtendedJson`` value to the ``OutputMode``
property:

.. io-code-block::

.. input:: /includes/fundamentals/code-examples/ExtendedJson.cs
:language: csharp
:start-after: start-write-ejson
:end-before: end-write-ejson
:dedent:

.. output::
:visible: false

{ "_id" : { "$oid" : "68094769744af81f368ff1c1" }, "CreatedAt" : { "$date" : { "$numberLong" : "1745438569994" } }, "NumViews" : { "$numberLong" : "1234567890" } }

API Documentation
-----------------

To learn more about the methods and classes used on this page, see the following API
documentation:

- `BsonDocument <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.BsonDocument.html>`__
- `BsonSerializer <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.Serialization.BsonSerializer.html>`__
- `ToJson() <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.BsonExtensionMethods.ToJson.html>`__
- `JsonWriter <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.IO.JsonWriter.html>`__
- `JsonReader <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.IO.JsonReader.html>`__
- `JsonWriterSettings <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.IO.JsonWriterSettings.html>`__
- `JsonReaderSettings <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.IO.JsonReaderSettings.html>`__
- `JsonOutputMode <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.IO.JsonOutputMode.html>`__
42 changes: 42 additions & 0 deletions source/includes/fundamentals/code-examples/ExtendedJson.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
using MongoDB.Bson;
using MongoDB.Bson.IO;
using MongoDB.Bson.Serialization;

public class ExtendedJson
{
public static void Main(string[] args)
{
{
// start-read-ejson
var ejson = "{\n\"_id\": { \"$oid\": \"573a1391f29313caabcd9637\" },\n \"createdAt\": { \"$date\": { \"$numberLong\": \"1601499609\" }},\n\"numViews\": { \"$numberLong\": \"36520312\" }\n}\n\n";

var document = BsonSerializer.Deserialize<BsonDocument>(ejson);
Console.WriteLine(document.ToJson());
// end-read-ejson
}

{
// start-write-ejson
var document = new MyDocument();
document.Id = ObjectId.GenerateNewId();
document.CreatedAt = DateTime.UtcNow;
document.NumViews = 1234567890;

var json = document.ToJson(new JsonWriterSettings
{
OutputMode = JsonOutputMode.CanonicalExtendedJson
});
Console.WriteLine(json);
// end-write-ejson
}
}
}

// start-custom-class
public class MyDocument
{
public ObjectId Id { get; set; }
public DateTime CreatedAt { get; set; }
public long NumViews { get; set; }
}
// end-custom-class
Loading