BSON_AS_JSON_WITH_OPTS(3)

πŸ’… BSON_AS_JSON_WITH_OPTS πŸ’…

okay so bestie, welcome to the bson_as_json_with_opts page, straight out of the libbson manual (section 3, iykyk). this one's a little baddie of a function and honestly? she ate. let's get into it ✨


✨ SYNOPSIS ✨

char *
bson_as_json_with_opts (const bson_t *bson, size_t *length, const bson_json_opts_t *opts);

like, that's her. that's the whole signature. gorgeous, no notes πŸ’…


πŸŽ€ PARAMETERS πŸŽ€

  • bson β€” a bson_t. the actual BSON thing you're turning into a string, bestie 🫢
  • length β€” an optional spot to stash the length of the resulting string. optional!! so you can pass NULL and she won't be mad at you πŸ’–
  • opts β€” a bson_json_opts_t. this is where you tell her how you want the encoding done πŸ‘‘

πŸ¦‹ DESCRIPTION πŸ¦‹

bson_as_json_with_opts() encodes bson as a UTF-8 string, either in the MongoDB Extended JSON format or in libbson's Legacy Extended JSON. literally her whole personality 🌈

so listen β€” the caller is responsible for freeing that resulting UTF-8 encoded string. that means you, bestie 😭 call bson_free() on the result when you're done with it. don't just leave her hanging, that's so not main character energy πŸ™ˆ

if length is non-NULL, length gets set to the length of the result in bytes. bytes, not vibes. important distinction πŸ’€

and the opts structure? that's the little vehicle for passing options into the encoding process πŸš—πŸ’¨ please refer to the documentation of bson_json_opts_t for more details β€” she's got lore, go read it πŸ“–βœ¨


πŸ“ RETURNS πŸ“

  • if it's successful β†’ a newly allocated UTF-8 encoded string comes back to you, and length is set. slay πŸ’š
  • upon failure β†’ NULL. and honestly? rude, but okay 😭
fr fr, remember that failure case exists. always vibe-check your return value before you start printing it everywhere 🫢

πŸ‘‘ EXAMPLE πŸ‘‘

okay this is my favorite part, watch her work:

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

see how she cleans up after herself? bson_free(str), bson_json_opts_destroy(opts), bson_destroy(b). three little cleanup lines, maximum responsibility, zero leaks. that's the energy we're bringing into 2026 ✨🧚


🌸 AUTHOR 🌸

MongoDB, Inc β€” yeah, them. the icons behind all this πŸ’œ


2009-present, MongoDB, Inc.


and that's the page!! πŸ¦‹ this was BSON_AS_JSON_WITH_OPTS(3) from libbson, version 2.5.6, dated Oct 09, 2026 β€” go forth and encode responsibly, bestie, mwah πŸ’…πŸ’–πŸŽ€

πŸ“¦ where this page comes from