BSON_AS_CANONICAL_EXTENDED_JSON(3)

πŸ’– BSON_AS_CANONICAL_EXTENDED_JSON πŸ’–

okay bestie, so this one lives in libbson and it's genuinely one of my faves β€” it's the glow-up where your raw BSON gets turned into a pretty little UTF-8 string. let's get into it ✨


✨ SYNOPSIS ✨

char *
bson_as_canonical_extended_json (const bson_t *bson, size_t *length);

πŸŽ€ PARAMETERS πŸŽ€

  • bson β€” a bson_t. that's the thing you're converting, no cap.
  • length β€” an optional spot to stash the length of the resulting string. optional!! so you can pass NULL and nobody's mad 🫢

πŸ¦‹ DESCRIPTION πŸ¦‹

bson_as_canonical_extended_json() encodes bson as a UTF-8 string in the Canonical Extended JSON. and if you wanna know what on earth the Extended JSON formats even are, it literally says: see MongoDB Extended JSON format for a description of Extended JSON formats. iykyk πŸ’…

okay important part, listen up: the caller is responsible for freeing that resulting UTF-8 encoded string β€” you do it by calling bson_free() with the result. don't just leave it there, that's not main character behavior, that's a leak 😭

and if length is non-NULL, it gets set to the length of the result in bytes. bytes, not vibes.


🌸 RETURNS 🌸

  • if it worked: a newly allocated UTF-8 encoded string, and length is set. slay ✨
  • if it didn't: NULL comes back. that's it, that's the failure state πŸ’€

πŸ“ EXAMPLE πŸ“

bson_t *b = BCON_NEW("foo", BCON_INT32(123));
char *str = bson_as_canonical_extended_json(b, NULL);
printf("Canonical Extended JSON: %s\n", str);
// Prints:
// Canonical Extended JSON: { "foo" : { "$numberInt" : "123" } }
bson_free(str);
bson_destroy(b);

see how bson_free(str) and bson_destroy(b) are right there at the end? that's the self-care part. do not skip it πŸ™ˆ


πŸ‘‘ AUTHOR πŸ‘‘

MongoDB, Inc


2009-present, MongoDB, Inc.


and that's the whole page, bestie πŸŽ€ this was the 2.5.6 libbson drop, dated Oct 09, 202…, so go forth and canonically extend your JSON πŸ’œπŸ¦‹β­

πŸ“¦ where this page comes from