<page xmlns="http://projectmallard.org/1.0/"
      type="topic"
      id="json">

  <title>JSON</title>

  <p>Libbson provides routines for converting to and from the JSON format. In particular, it supports the <link href="http://docs.mongodb.org/manual/reference/mongodb-extended-json/">MongoDB extended JSON</link> format.</p>

  <section id="to-json">
    <info><link type="guide" xref="index#json"/></info>
    <title>Converting BSON to JSON</title>
    <p>There are often times where you might want to convert a BSON document to JSON. It is convenient for debugging as well as an interchange format. To help with this, Libbson contains the function <code xref="bson_as_json">bson_as_json()</code>.</p>
    <example>
      <title>Convert to JSON</title>
      <code mime="text/x-csrc"><![CDATA[bson_t *b;
size_t len;
char *str;

b = BCON_NEW ("a", BCON_INT32 (1));

str = bson_as_json (b, &len);
printf ("%s\n", str);
bson_free (str);

bson_destroy (b);]]></code>
      <screen><output>{ "a" : 1 }</output></screen>
    </example>
  </section>

  <section id="from-json">
    <title>Converting JSON to BSON</title>
    <info><link type="guide" xref="index#json"/></info>
    <p>Converting back from JSON is also useful and common enough that we added <code xref="bson_init_from_json">bson_init_from_json()</code> and <code xref="bson_new_from_json">bson_new_from_json()</code>.</p>
    <p>The following example creates a new <code xref="bson_t">bson_t</code> from the JSON string <code>{"a":1}</code>.</p>
    <example>
      <title>Convert from JSON</title>
      <code mime="text/x-csrc"><![CDATA[bson_t *b;
bson_error_t error;

b = bson_new_from_json ("{\"a\":1}", -1, &error);

if (!b) {
   printf ("Error: %s\n", error.message);
} else {
   bson_destroy (b);
}]]></code>
    </example>
  </section>

  <section id="streaming-json-parsing">
    <title>Streaming JSON Parsing</title>
    <info><link type="guide" xref="index#json"/></info>
    <p>Libbson provides <code xref="bson_json_reader_t">bson_json_reader_t</code> to allow for parsing a sequence of JSON documents into BSON. The interface is similar to <code xref="bson_reader_t">bson_reader_t</code> but expects the input to be in the <link href="http://docs.mongodb.org/manual/reference/mongodb-extended-json/">MongoDB extended JSON</link> format.</p>
    <example>
      <title><file>json-to-bson.c</file></title>
      <code mime="text/x-csrc"><include parse="text" href="../examples/json-to-bson.c" xmlns="http://www.w3.org/2001/XInclude" /></code>
    </example>
  </section>

  <section id="example">
    <title>Examples</title>
    <p>The following example reads BSON documents from <code>stdin</code> and prints them to <code>stdout</code> as JSON.</p>
    <example>
      <title><file>bson-to-json.c</file></title>
      <code mime="text/x-csrc"><include parse="text" href="../examples/bson-to-json.c" xmlns="http://www.w3.org/2001/XInclude" /></code>
    </example>
  </section>

</page>
