BSON (Binary JSON) is a binary format in which zero or more ordered key/value pairs are stored as a single entity (a so-called document).
The library uses the following mapping from JSON values types to BSON types:
JSON value type | value/range | BSON type | marker |
null | null | null | 0x0A |
boolean | true , false | boolean | 0x08 |
number_integer | -9223372036854775808..-2147483649 | int64 | 0x12 |
number_integer | -2147483648..2147483647 | int32 | 0x10 |
number_integer | 2147483648..9223372036854775807 | int64 | 0x12 |
number_unsigned | 0..2147483647 | int32 | 0x10 |
number_unsigned | 2147483648..9223372036854775807 | int64 | 0x12 |
number_unsigned | 9223372036854775808..18446744073709551615 | – | – |
number_float | any value | double | 0x01 |
string | any value | string | 0x02 |
array | any value | document | 0x04 |
object | any value | document | 0x03 |
- Warning
- The mapping is incomplete, since only JSON-objects (and things contained therein) can be serialized to BSON. Also, integers larger than 9223372036854775807 cannot be serialized to BSON, and the keys may not contain U+0000, since they are serialized a zero-terminated c-strings.
- Exceptions
-
out_of_range.407 | if j.is_number_unsigned() && j.get<std::uint64_t>() > 9223372036854775807 |
out_of_range.409 | if a key in j contains a NULL (U+0000) |
type_error.317 | if !j.is_object() |
- Precondition
- The input
j
is required to be an object: j.is_object() == true
.
- Note
- Any BSON output created via to_bson can be successfully parsed by from_bson.
- Parameters
-
[in] | j | JSON value to serialize |
- Returns
- BSON serialization as byte vector
- Complexity
- Linear in the size of the JSON value j.
- Example
- The example shows the serialization of a JSON value to a byte vector in BSON format.
3 #include <nlohmann/json.hpp>
10 json j = R
"({"compact": true, "schema": 0})"_json;
18 std::cout <<
"0x" << std::hex << std::setw(2) << std::setfill(
'0') << (int)
byte <<
" ";
20 std::cout << std::endl;
Output (play with this example online): 0x1b 0x00 0x00 0x00 0x08 0x63 0x6f 0x6d 0x70 0x61 0x63 0x74 0x00 0x01 0x10 0x73 0x63 0x68 0x65 0x6d 0x61 0x00 0x00 0x00 0x00 0x00 0x00
The example code above can be translated withg++ -std=c++11 -Isingle_include doc/examples/to_bson.cpp -o to_bson
- See also
- http://bsonspec.org/spec.html
-
from_bson(detail::input_adapter&&, const bool strict) for the analogous deserialization
-
to_ubjson(const basic_json&, const bool, const bool) for the related UBJSON format
-
to_cbor(const basic_json&) for the related CBOR format
-
to_msgpack(const basic_json&) for the related MessagePack format
Definition at line 21398 of file json.hpp.