BSON_JSON(3)

πŸ“¦
version 1.26.0 Β· 3 versions
, in ubuntu noble

πŸ’– BSON_JSON πŸ’–

okay bestie, so this is a libbson manual page β€” that's the C library situation, iykyk β€” and it's literally all about converting between BSON and JSON. and not just any JSON, no no. it supports the MongoDB extended JSON format, which is the ✨fancy✨ version. slay.


πŸ¦‹ CONVERTING BSON TO JSON πŸ¦‹

so there are <em>so</em> many times when you're gonna want to turn a BSON document into JSON β€” for debugging, for sending it somewhere else, whatever. interchange format vibes. and Libbson has your back with two iconic little functions: bson_as_canonical_extended_json() and bson_as_relaxed_extended_json().

the canonical format keeps all the BSON type information for values that might get ambiguous in JSON (like, hello, numeric types πŸ’€). here's the moment:

bson_t *b;
size_t len;
char *str;

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

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

bson_destroy (b);

{ "a" : { "$numberInt": "1" } }

and then there's the relaxed format, which prefers plain JSON primitives for numbers and is your girl when you don't actually need type fidelity:

bson_t *b;
size_t len;
char *str;

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

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

bson_destroy (b);

{ "a" : 1 }

see how much chiller that is? obsessed. 🫢


🌸 CONVERTING JSON TO BSON 🌸

going the other way is also useful and honestly common enough that we added bson_init_from_json() and bson_new_from_json(). besties, it's a two-way street.

this next one builds a fresh bson_t out of the JSON string {"a":1}. iconic:

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

🧚 STREAMING JSON PARSING 🧚

Libbson gives you bson_json_reader_t so you can parse a whole sequence of JSON documents into BSON. the interface is similar to bson_reader_t, except it expects the input to be in MongoDB extended JSON format. noted. πŸ’…

/*
 * Copyright 2013 MongoDB, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 * This program will print each JSON document contained in the provided files
 * as a BSON string to STDOUT.
 */

#include <bson/bson.h>
#include <stdlib.h>
#include <stdio.h>

int
main (int argc, char *argv[])
{
   bson_json_reader_t *reader;
   bson_error_t error;
   const char *filename;
   bson_t doc = BSON_INITIALIZER;
   int i;
   int b;

   /*
    * Print program usage if no arguments are provided.
    */
   if (argc == 1) {
      fprintf (stderr, "usage: %s FILE...\n", argv[0]);
      return 1;
   }

   /*
    * Process command line arguments expecting each to be a filename.
    */
   for (i = 1; i < argc; i++) {
      filename = argv[i];

      /*
       * Open the filename provided in command line arguments.
       */
      if (0 == strcmp (filename, "-")) {
         reader = bson_json_reader_new_from_fd (STDIN_FILENO, false);
      } else {
         if (!(reader = bson_json_reader_new_from_file (filename, &error))) {
            fprintf (
               stderr, "Failed to open \"%s\": %s\n", filename, error.message);
            continue;
         }
      }

      /*
       * Convert each incoming document to BSON and print to stdout.
       */
      while ((b = bson_json_reader_read (reader, &doc, &error))) {
         if (b < 0) {
            fprintf (stderr, "Error in json parsing:\n%s\n", error.message);
            abort ();
         }

         if (fwrite (bson_get_data (&doc), 1, doc.len, stdout) != doc.len) {
            fprintf (stderr, "Failed to write to stdout, exiting.\n");
            exit (1);
         }
         bson_reinit (&doc);
      }

      bson_json_reader_destroy (reader);
      bson_destroy (&doc);
   }

   return 0;
}

✨ EXAMPLES ✨

this next one reads BSON documents from stdin and prints them to stdout as JSON. a whole pipeline moment:

/*
 * Copyright 2013 MongoDB, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 * This program will print each BSON document contained in the provided files
 * as a JSON string to STDOUT.
 */

#include <bson/bson.h>
#include <stdio.h>

int
main (int argc, char *argv[])
{
   bson_reader_t *reader;
   const bson_t *b;
   bson_error_t error;
   const char *filename;
   char *str;
   int i;

   /*
    * Print program usage if no arguments are provided.
    */
   if (argc == 1) {
      fprintf (stderr, "usage: %s [FILE | -]...\nUse - for STDIN.\n", argv[0]);
      return 1;
   }

   /*
    * Process command line arguments expecting each to be a filename.
    */
   for (i = 1; i < argc; i++) {
      filename = argv[i];

      if (strcmp (filename, "-") == 0) {
         reader = bson_reader_new_from_fd (STDIN_FILENO, false);
      } else {
         if (!(reader = bson_reader_new_from_file (filename, &error))) {
            fprintf (
               stderr, "Failed to open \"%s\": %s\n", filename, error.message);
            continue;
         }
      }

      /*
       * Convert each incoming document to JSON and print to stdout.
       */
      while ((b = bson_reader_read (reader, NULL))) {
         str = bson_as_canonical_extended_json (b, NULL);
         fprintf (stdout, "%s\n", str);
         bson_free (str);
      }

      /*
       * Cleanup after our reader, which closes the file descriptor.
       */
      bson_reader_destroy (reader);
   }

   return 0;
}

πŸ‘‘ AUTHOR πŸ‘‘

MongoDB, Inc

2017-present, MongoDB, Inc


and that's the whole page bestie!! no cap, that's everything. πŸ’–

okay so tiny little sign-off tea: this was libbson version 1.26.0, dated Mar 31, 2024, and yes the page is literally called BSON_JSON(3) β€” the whole thing, done, periodt. πŸ¦‹βœ¨

πŸ“¦ where this page comes from