From 55f10f44a9adf1abc0dbeb3c4ca1b6417faae434 Mon Sep 17 00:00:00 2001 From: <> Date: Wed, 8 Mar 2023 12:43:29 +0000 Subject: [PATCH] Deployed fe4b663 with MkDocs version: 1.4.2 --- .nojekyll | 0 404.html | 1 + api/adl_serializer/from_json/index.html | 104 + api/adl_serializer/index.html | 15 + api/adl_serializer/to_json/index.html | 38 + api/basic_json/accept/index.html | 37 + api/basic_json/array/index.html | 25 + api/basic_json/array_t/index.html | 17 + api/basic_json/at/index.html | 508 ++ api/basic_json/back/index.html | 52 + api/basic_json/basic_json/index.html | 462 ++ api/basic_json/begin/index.html | 20 + api/basic_json/binary/index.html | 27 + api/basic_json/binary_t/index.html | 13 + api/basic_json/boolean_t/index.html | 13 + api/basic_json/cbegin/index.html | 19 + api/basic_json/cbor_tag_handler_t/index.html | 38 + api/basic_json/cend/index.html | 22 + api/basic_json/clear/index.html | 44 + api/basic_json/contains/index.html | 104 + api/basic_json/count/index.html | 49 + api/basic_json/crbegin/index.html | 19 + api/basic_json/crend/index.html | 22 + .../default_object_comparator_t/index.html | 17 + api/basic_json/diff/index.html | 66 + api/basic_json/dump/index.html | 108 + api/basic_json/emplace/index.html | 40 + api/basic_json/emplace_back/index.html | 31 + api/basic_json/empty/index.html | 45 + api/basic_json/end/index.html | 23 + api/basic_json/erase/index.html | 151 + api/basic_json/error_handler_t/index.html | 33 + api/basic_json/exception/index.html | 24 + api/basic_json/find/index.html | 58 + api/basic_json/flatten/index.html | 46 + api/basic_json/from_bjdata/index.html | 35 + api/basic_json/from_bson/index.html | 36 + api/basic_json/from_cbor/index.html | 38 + api/basic_json/from_msgpack/index.html | 35 + api/basic_json/from_ubjson/index.html | 35 + api/basic_json/front/index.html | 38 + api/basic_json/get/index.html | 106 + api/basic_json/get_allocator/index.html | 21 + api/basic_json/get_binary/index.html | 21 + api/basic_json/get_ptr/index.html | 29 + api/basic_json/get_ref/index.html | 35 + api/basic_json/get_to/index.html | 78 + api/basic_json/index.html | 81 + api/basic_json/input_format_t/index.html | 126 + api/basic_json/insert/index.html | 119 + api/basic_json/invalid_iterator/index.html | 25 + api/basic_json/is_array/index.html | 41 + api/basic_json/is_binary/index.html | 41 + api/basic_json/is_boolean/index.html | 41 + api/basic_json/is_discarded/index.html | 43 + api/basic_json/is_null/index.html | 41 + api/basic_json/is_number/index.html | 45 + api/basic_json/is_number_float/index.html | 41 + api/basic_json/is_number_integer/index.html | 41 + api/basic_json/is_number_unsigned/index.html | 41 + api/basic_json/is_object/index.html | 41 + api/basic_json/is_primitive/index.html | 45 + api/basic_json/is_string/index.html | 41 + api/basic_json/is_structured/index.html | 45 + api/basic_json/items/index.html | 50 + api/basic_json/json_base_class_t/index.html | 94 + api/basic_json/json_serializer/index.html | 57 + api/basic_json/max_size/index.html | 34 + api/basic_json/merge_patch/index.html | 67 + api/basic_json/meta/index.html | 30 + api/basic_json/number_float_t/index.html | 13 + api/basic_json/number_integer_t/index.html | 13 + api/basic_json/number_unsigned_t/index.html | 13 + api/basic_json/object/index.html | 34 + api/basic_json/object_comparator_t/index.html | 17 + api/basic_json/object_t/index.html | 31 + api/basic_json/operator+=/index.html | 99 + api/basic_json/operator=/index.html | 27 + api/basic_json/operator[]/index.html | 286 + api/basic_json/operator_ValueType/index.html | 79 + api/basic_json/operator_eq/index.html | 118 + api/basic_json/operator_ge/index.html | 37 + api/basic_json/operator_gt/index.html | 37 + api/basic_json/operator_gtgt/index.html | 15 + api/basic_json/operator_le/index.html | 37 + .../operator_literal_json/index.html | 15 + .../operator_literal_json_pointer/index.html | 15 + api/basic_json/operator_lt/index.html | 37 + api/basic_json/operator_ltlt/index.html | 15 + api/basic_json/operator_ne/index.html | 72 + api/basic_json/operator_spaceship/index.html | 98 + api/basic_json/operator_value_t/index.html | 48 + api/basic_json/other_error/index.html | 34 + api/basic_json/out_of_range/index.html | 24 + api/basic_json/parse/index.html | 336 + api/basic_json/parse_error/index.html | 25 + api/basic_json/parse_event_t/index.html | 9 + api/basic_json/parser_callback_t/index.html | 87 + api/basic_json/patch/index.html | 46 + api/basic_json/patch_inplace/index.html | 50 + api/basic_json/push_back/index.html | 99 + api/basic_json/rbegin/index.html | 20 + api/basic_json/rend/index.html | 23 + api/basic_json/sax_parse/index.html | 184 + api/basic_json/size/index.html | 40 + api/basic_json/std_hash/index.html | 31 + api/basic_json/std_swap/index.html | 29 + api/basic_json/string_t/index.html | 13 + api/basic_json/swap/index.html | 129 + api/basic_json/to_bjdata/index.html | 79 + api/basic_json/to_bson/index.html | 30 + api/basic_json/to_cbor/index.html | 30 + api/basic_json/to_msgpack/index.html | 30 + api/basic_json/to_string/index.html | 31 + api/basic_json/to_ubjson/index.html | 79 + api/basic_json/type/index.html | 38 + api/basic_json/type_error/index.html | 24 + api/basic_json/type_name/index.html | 37 + api/basic_json/unflatten/index.html | 46 + api/basic_json/update/index.html | 113 + api/basic_json/value/index.html | 121 + api/basic_json/value_t/index.html | 49 + api/basic_json/~basic_json/index.html | 2 + .../byte_container_with_subtype/index.html | 37 + .../clear_subtype/index.html | 25 + .../has_subtype/index.html | 23 + api/byte_container_with_subtype/index.html | 3 + .../set_subtype/index.html | 26 + .../subtype/index.html | 26 + api/json/index.html | 68 + api/json_pointer/back/index.html | 19 + api/json_pointer/empty/index.html | 26 + api/json_pointer/index.html | 3 + api/json_pointer/json_pointer/index.html | 52 + api/json_pointer/operator_eq/index.html | 85 + api/json_pointer/operator_ne/index.html | 75 + api/json_pointer/operator_slash/index.html | 31 + api/json_pointer/operator_slasheq/index.html | 36 + api/json_pointer/operator_string/index.html | 15 + api/json_pointer/operator_string_t/index.html | 27 + api/json_pointer/parent_pointer/index.html | 23 + api/json_pointer/pop_back/index.html | 27 + api/json_pointer/push_back/index.html | 29 + api/json_pointer/string_t/index.html | 17 + api/json_pointer/to_string/index.html | 49 + api/json_sax/binary/index.html | 119 + api/json_sax/boolean/index.html | 170 + api/json_sax/end_array/index.html | 170 + api/json_sax/end_object/index.html | 170 + api/json_sax/index.html | 3 + api/json_sax/key/index.html | 170 + api/json_sax/null/index.html | 170 + api/json_sax/number_float/index.html | 170 + api/json_sax/number_integer/index.html | 170 + api/json_sax/number_unsigned/index.html | 170 + api/json_sax/parse_error/index.html | 172 + api/json_sax/start_array/index.html | 170 + api/json_sax/start_object/index.html | 170 + api/json_sax/string/index.html | 170 + api/macros/index.html | 1 + api/macros/json_assert/index.html | 27 + api/macros/json_diagnostics/index.html | 47 + .../index.html | 92 + api/macros/json_has_cpp_11/index.html | 9 + api/macros/json_has_filesystem/index.html | 7 + api/macros/json_has_ranges/index.html | 6 + .../json_has_three_way_comparison/index.html | 6 + api/macros/json_no_io/index.html | 7 + api/macros/json_noexception/index.html | 7 + .../index.html | 4 + .../index.html | 7 + api/macros/json_throw_user/index.html | 24 + api/macros/json_use_global_udls/index.html | 32 + .../json_use_implicit_conversions/index.html | 7 + .../index.html | 7 + .../nlohmann_define_type_intrusive/index.html | 214 + .../index.html | 196 + api/macros/nlohmann_json_namespace/index.html | 17 + .../nlohmann_json_namespace_begin/index.html | 43 + .../index.html | 17 + .../nlohmann_json_serialize_enum/index.html | 104 + .../nlohmann_json_version_major/index.html | 17 + api/operator_gtgt/index.html | 41 + api/operator_literal_json/index.html | 24 + api/operator_literal_json_pointer/index.html | 22 + api/operator_ltlt/index.html | 60 + api/ordered_json/index.html | 21 + api/ordered_map/index.html | 54 + assets/images/favicon.png | Bin 0 -> 1870 bytes assets/javascripts/bundle.5a2dcb6a.min.js | 29 + assets/javascripts/bundle.5a2dcb6a.min.js.map | 8 + .../javascripts/extra/bundle.5f09fbc3.min.js | 18 + .../extra/bundle.5f09fbc3.min.js.map | 8 + assets/javascripts/lunr/min/lunr.ar.min.js | 1 + assets/javascripts/lunr/min/lunr.da.min.js | 18 + assets/javascripts/lunr/min/lunr.de.min.js | 18 + assets/javascripts/lunr/min/lunr.du.min.js | 18 + assets/javascripts/lunr/min/lunr.es.min.js | 18 + assets/javascripts/lunr/min/lunr.fi.min.js | 18 + assets/javascripts/lunr/min/lunr.fr.min.js | 18 + assets/javascripts/lunr/min/lunr.hi.min.js | 1 + assets/javascripts/lunr/min/lunr.hu.min.js | 18 + assets/javascripts/lunr/min/lunr.it.min.js | 18 + assets/javascripts/lunr/min/lunr.ja.min.js | 1 + assets/javascripts/lunr/min/lunr.jp.min.js | 1 + assets/javascripts/lunr/min/lunr.ko.min.js | 1 + assets/javascripts/lunr/min/lunr.multi.min.js | 1 + assets/javascripts/lunr/min/lunr.nl.min.js | 18 + assets/javascripts/lunr/min/lunr.no.min.js | 18 + assets/javascripts/lunr/min/lunr.pt.min.js | 18 + assets/javascripts/lunr/min/lunr.ro.min.js | 18 + assets/javascripts/lunr/min/lunr.ru.min.js | 18 + .../lunr/min/lunr.stemmer.support.min.js | 1 + assets/javascripts/lunr/min/lunr.sv.min.js | 18 + assets/javascripts/lunr/min/lunr.ta.min.js | 1 + assets/javascripts/lunr/min/lunr.th.min.js | 1 + assets/javascripts/lunr/min/lunr.tr.min.js | 18 + assets/javascripts/lunr/min/lunr.vi.min.js | 1 + assets/javascripts/lunr/min/lunr.zh.min.js | 1 + assets/javascripts/lunr/tinyseg.js | 206 + assets/javascripts/lunr/wordcut.js | 6708 +++++++++++++++++ .../workers/search.16e2a7d4.min.js | 48 + .../workers/search.16e2a7d4.min.js.map | 8 + assets/stylesheets/extra.0d2c79a8.min.css | 1 + assets/stylesheets/extra.0d2c79a8.min.css.map | 1 + assets/stylesheets/main.975780f9.min.css | 1 + assets/stylesheets/main.975780f9.min.css.map | 1 + assets/stylesheets/palette.2505c338.min.css | 1 + .../stylesheets/palette.2505c338.min.css.map | 1 + css/custom.css | 4 + examples/README.cpp | 39 + examples/README.output | 27 + examples/accept__string.cpp | 26 + examples/accept__string.output | 1 + examples/array.cpp | 19 + examples/array.output | 4 + examples/array_t.cpp | 10 + examples/array_t.output | 1 + examples/at__json_pointer.cpp | 104 + examples/at__json_pointer.output | 12 + examples/at__json_pointer_const.cpp | 80 + examples/at__json_pointer_const.output | 9 + examples/at__keytype.c++17.cpp | 50 + examples/at__keytype.c++17.output | 4 + examples/at__keytype_const.c++17.cpp | 44 + examples/at__keytype_const.c++17.output | 3 + examples/at__object_t_key_type.cpp | 48 + examples/at__object_t_key_type.output | 4 + examples/at__object_t_key_type_const.cpp | 42 + examples/at__object_t_key_type_const.output | 3 + examples/at__size_type.cpp | 43 + examples/at__size_type.output | 4 + examples/at__size_type_const.cpp | 37 + examples/at__size_type_const.output | 3 + examples/back.cpp | 38 + examples/back.output | 7 + examples/basic_json__CompatibleType.cpp | 218 + examples/basic_json__CompatibleType.output | 39 + examples/basic_json__InputIt_InputIt.cpp | 32 + examples/basic_json__InputIt_InputIt.output | 4 + examples/basic_json__basic_json.cpp | 17 + examples/basic_json__basic_json.output | 2 + examples/basic_json__copyassignment.cpp | 18 + examples/basic_json__copyassignment.output | 2 + examples/basic_json__list_init_t.cpp | 21 + examples/basic_json__list_init_t.output | 5 + examples/basic_json__moveconstructor.cpp | 17 + examples/basic_json__moveconstructor.output | 2 + examples/basic_json__nullptr_t.cpp | 16 + examples/basic_json__nullptr_t.output | 2 + examples/basic_json__size_type_basic_json.cpp | 18 + .../basic_json__size_type_basic_json.output | 3 + examples/basic_json__value_t.cpp | 25 + examples/basic_json__value_t.output | 7 + examples/begin.cpp | 16 + examples/begin.output | 1 + examples/binary.cpp | 16 + examples/binary.output | 1 + examples/binary_t.cpp | 10 + examples/binary_t.output | 1 + examples/boolean_t.cpp | 10 + examples/boolean_t.output | 1 + ...h_subtype__byte_container_with_subtype.cpp | 23 + ...ubtype__byte_container_with_subtype.output | 3 + ..._container_with_subtype__clear_subtype.cpp | 21 + ...ntainer_with_subtype__clear_subtype.output | 2 + ...te_container_with_subtype__has_subtype.cpp | 19 + ...container_with_subtype__has_subtype.output | 2 + ...te_container_with_subtype__set_subtype.cpp | 22 + ...container_with_subtype__set_subtype.output | 2 + .../byte_container_with_subtype__subtype.cpp | 22 + ...yte_container_with_subtype__subtype.output | 2 + examples/cbegin.cpp | 16 + examples/cbegin.output | 1 + examples/cbor_tag_handler_t.cpp | 28 + examples/cbor_tag_handler_t.output | 3 + examples/cend.cpp | 19 + examples/cend.output | 1 + examples/clear.cpp | 34 + examples/clear.output | 7 + examples/contains__json_pointer.cpp | 43 + examples/contains__json_pointer.output | 7 + examples/contains__keytype.c++17.cpp | 20 + examples/contains__keytype.c++17.output | 3 + examples/contains__object_t_key_type.cpp | 18 + examples/contains__object_t_key_type.output | 3 + examples/count__keytype.c++17.cpp | 20 + examples/count__keytype.c++17.output | 2 + examples/count__object_t_key_type.cpp | 18 + examples/count__object_t_key_type.output | 2 + examples/crbegin.cpp | 16 + examples/crbegin.output | 1 + examples/crend.cpp | 19 + examples/crend.output | 1 + examples/default_object_comparator_t.cpp | 11 + examples/default_object_comparator_t.output | 2 + examples/diagnostics_extended.cpp | 22 + examples/diagnostics_extended.output | 1 + examples/diagnostics_standard.cpp | 20 + examples/diagnostics_standard.output | 1 + examples/diff.cpp | 37 + examples/diff.output | 25 + examples/dump.cpp | 48 + examples/dump.output | 55 + examples/emplace.cpp | 31 + examples/emplace.output | 6 + examples/emplace_back.cpp | 24 + examples/emplace_back.output | 4 + examples/empty.cpp | 30 + examples/empty.output | 9 + examples/end.cpp | 19 + examples/end.output | 1 + examples/erase__IteratorType.cpp | 31 + examples/erase__IteratorType.output | 6 + examples/erase__IteratorType_IteratorType.cpp | 31 + .../erase__IteratorType_IteratorType.output | 6 + examples/erase__keytype.c++17.cpp | 20 + examples/erase__keytype.c++17.output | 2 + examples/erase__object_t_key_type.cpp | 18 + examples/erase__object_t_key_type.output | 2 + examples/erase__size_type.cpp | 16 + examples/erase__size_type.output | 1 + examples/error_handler_t.cpp | 24 + examples/error_handler_t.output | 3 + examples/exception.cpp | 20 + examples/exception.output | 2 + examples/find__keytype.c++17.cpp | 22 + examples/find__keytype.c++17.output | 3 + examples/find__object_t_key_type.cpp | 20 + examples/find__object_t_key_type.output | 3 + examples/flatten.cpp | 32 + examples/flatten.output | 12 + examples/from_bjdata.cpp | 20 + examples/from_bjdata.output | 4 + examples/from_bson.cpp | 21 + examples/from_bson.output | 4 + examples/from_cbor.cpp | 20 + examples/from_cbor.output | 4 + examples/from_json__default_constructible.cpp | 37 + .../from_json__default_constructible.output | 1 + .../from_json__non_default_constructible.cpp | 53 + ...rom_json__non_default_constructible.output | 1 + examples/from_msgpack.cpp | 20 + examples/from_msgpack.output | 4 + examples/from_ubjson.cpp | 20 + examples/from_ubjson.output | 4 + examples/front.cpp | 29 + examples/front.output | 6 + examples/get__PointerType.cpp | 21 + examples/get__PointerType.output | 2 + examples/get__ValueType_const.cpp | 50 + examples/get__ValueType_const.output | 11 + examples/get_allocator.cpp | 18 + examples/get_allocator.output | 1 + examples/get_binary.cpp | 16 + examples/get_binary.output | 1 + examples/get_ptr.cpp | 21 + examples/get_ptr.output | 2 + examples/get_ref.cpp | 27 + examples/get_ref.output | 2 + examples/get_to.cpp | 60 + examples/get_to.output | 11 + examples/insert.cpp | 17 + examples/insert.output | 2 + examples/insert__count.cpp | 17 + examples/insert__count.output | 2 + examples/insert__ilist.cpp | 17 + examples/insert__ilist.output | 2 + examples/insert__range.cpp | 20 + examples/insert__range.output | 2 + examples/insert__range_object.cpp | 21 + examples/insert__range_object.output | 3 + examples/invalid_iterator.cpp | 21 + examples/invalid_iterator.output | 2 + examples/is_array.cpp | 30 + examples/is_array.output | 9 + examples/is_binary.cpp | 30 + examples/is_binary.output | 9 + examples/is_boolean.cpp | 30 + examples/is_boolean.output | 9 + examples/is_discarded.cpp | 30 + examples/is_discarded.output | 9 + examples/is_null.cpp | 30 + examples/is_null.output | 9 + examples/is_number.cpp | 30 + examples/is_number.output | 9 + examples/is_number_float.cpp | 30 + examples/is_number_float.output | 9 + examples/is_number_integer.cpp | 30 + examples/is_number_integer.output | 9 + examples/is_number_unsigned.cpp | 30 + examples/is_number_unsigned.output | 9 + examples/is_object.cpp | 30 + examples/is_object.output | 9 + examples/is_primitive.cpp | 30 + examples/is_primitive.output | 9 + examples/is_string.cpp | 30 + examples/is_string.output | 9 + examples/is_structured.cpp | 30 + examples/is_structured.output | 9 + examples/items.cpp | 23 + examples/items.output | 7 + examples/json_base_class_t.cpp | 88 + examples/json_base_class_t.output | 4 + examples/json_lines.cpp | 22 + examples/json_lines.output | 4 + examples/json_pointer.cpp | 47 + examples/json_pointer.output | 3 + examples/json_pointer__back.cpp | 15 + examples/json_pointer__back.output | 2 + examples/json_pointer__empty.cpp | 20 + examples/json_pointer__empty.output | 4 + examples/json_pointer__operator__equal.cpp | 19 + examples/json_pointer__operator__equal.output | 4 + ...on_pointer__operator__equal_stringtype.cpp | 33 + ...pointer__operator__equal_stringtype.output | 4 + examples/json_pointer__operator__notequal.cpp | 19 + .../json_pointer__operator__notequal.output | 4 + ...pointer__operator__notequal_stringtype.cpp | 32 + ...nter__operator__notequal_stringtype.output | 4 + examples/json_pointer__operator_add.cpp | 23 + examples/json_pointer__operator_add.output | 4 + .../json_pointer__operator_add_binary.cpp | 19 + .../json_pointer__operator_add_binary.output | 3 + examples/json_pointer__operator_string_t.cpp | 19 + .../json_pointer__operator_string_t.output | 2 + examples/json_pointer__parent_pointer.cpp | 18 + examples/json_pointer__parent_pointer.output | 3 + examples/json_pointer__pop_back.cpp | 21 + examples/json_pointer__pop_back.output | 4 + examples/json_pointer__push_back.cpp | 21 + examples/json_pointer__push_back.output | 4 + examples/json_pointer__string_t.cpp | 13 + examples/json_pointer__string_t.output | 2 + examples/json_pointer__to_string.cpp | 34 + examples/json_pointer__to_string.output | 12 + examples/max_size.cpp | 25 + examples/max_size.output | 7 + examples/merge_patch.cpp | 41 + examples/merge_patch.output | 11 + examples/meta.cpp | 11 + examples/meta.output | 17 + ...lohmann_define_type_intrusive_explicit.cpp | 60 + ...mann_define_type_intrusive_explicit.output | 2 + .../nlohmann_define_type_intrusive_macro.cpp | 48 + ...lohmann_define_type_intrusive_macro.output | 2 + ...e_type_intrusive_with_default_explicit.cpp | 55 + ...ype_intrusive_with_default_explicit.output | 2 + ...fine_type_intrusive_with_default_macro.cpp | 42 + ...e_type_intrusive_with_default_macro.output | 2 + ...ann_define_type_non_intrusive_explicit.cpp | 53 + ..._define_type_non_intrusive_explicit.output | 2 + ...ohmann_define_type_non_intrusive_macro.cpp | 41 + ...ann_define_type_non_intrusive_macro.output | 2 + ...pe_non_intrusive_with_default_explicit.cpp | 53 + ...non_intrusive_with_default_explicit.output | 2 + ..._type_non_intrusive_with_default_macro.cpp | 40 + ...pe_non_intrusive_with_default_macro.output | 2 + examples/nlohmann_json_namespace.cpp | 14 + examples/nlohmann_json_namespace.output | 1 + .../nlohmann_json_namespace_begin.c++17.cpp | 33 + ...nlohmann_json_namespace_begin.c++17.output | 1 + .../nlohmann_json_namespace_no_version.cpp | 13 + .../nlohmann_json_namespace_no_version.output | 1 + examples/nlohmann_json_serialize_enum.cpp | 59 + examples/nlohmann_json_serialize_enum.output | 3 + examples/nlohmann_json_serialize_enum_2.cpp | 33 + .../nlohmann_json_serialize_enum_2.output | 3 + examples/nlohmann_json_version.cpp | 12 + examples/nlohmann_json_version.output | 1 + examples/number_float_t.cpp | 10 + examples/number_float_t.output | 1 + examples/number_integer_t.cpp | 10 + examples/number_integer_t.output | 1 + examples/number_unsigned_t.cpp | 10 + examples/number_unsigned_t.output | 1 + examples/object.cpp | 28 + examples/object.output | 4 + examples/object_comparator_t.cpp | 11 + examples/object_comparator_t.output | 2 + examples/object_t.cpp | 10 + examples/object_t.output | 1 + examples/operator__ValueType.cpp | 60 + examples/operator__ValueType.output | 12 + examples/operator__equal.cpp | 24 + examples/operator__equal.output | 4 + examples/operator__equal__nullptr_t.cpp | 22 + examples/operator__equal__nullptr_t.output | 5 + examples/operator__equal__specializations.cpp | 16 + .../operator__equal__specializations.output | 2 + examples/operator__greater.cpp | 24 + examples/operator__greater.output | 4 + examples/operator__greaterequal.cpp | 24 + examples/operator__greaterequal.output | 4 + examples/operator__less.cpp | 24 + examples/operator__less.output | 4 + examples/operator__lessequal.cpp | 24 + examples/operator__lessequal.output | 4 + examples/operator__notequal.cpp | 24 + examples/operator__notequal.output | 4 + examples/operator__notequal__nullptr_t.cpp | 22 + examples/operator__notequal__nullptr_t.output | 5 + examples/operator__value_t.cpp | 38 + examples/operator__value_t.output | 8 + examples/operator_array__json_pointer.cpp | 49 + examples/operator_array__json_pointer.output | 8 + .../operator_array__json_pointer_const.cpp | 25 + .../operator_array__json_pointer_const.output | 4 + examples/operator_array__keytype.c++17.cpp | 34 + examples/operator_array__keytype.c++17.output | 19 + .../operator_array__keytype_const.c++17.cpp | 18 + ...operator_array__keytype_const.c++17.output | 1 + .../operator_array__object_t_key_type.cpp | 32 + .../operator_array__object_t_key_type.output | 19 + ...perator_array__object_t_key_type_const.cpp | 16 + ...ator_array__object_t_key_type_const.output | 1 + examples/operator_array__size_type.cpp | 25 + examples/operator_array__size_type.output | 3 + examples/operator_array__size_type_const.cpp | 13 + .../operator_array__size_type_const.output | 1 + examples/operator_deserialize.cpp | 26 + examples/operator_deserialize.output | 13 + examples/operator_literal_json.cpp | 13 + examples/operator_literal_json.output | 4 + examples/operator_literal_json_pointer.cpp | 14 + examples/operator_literal_json_pointer.output | 1 + examples/operator_ltlt__basic_json.cpp | 21 + examples/operator_ltlt__basic_json.output | 22 + examples/operator_ltlt__json_pointer.cpp | 13 + examples/operator_ltlt__json_pointer.output | 1 + ...rator_spaceship__const_reference.c++20.cpp | 41 + ...or_spaceship__const_reference.c++20.output | 4 + .../operator_spaceship__scalartype.c++20.cpp | 41 + ...perator_spaceship__scalartype.c++20.output | 4 + examples/ordered_json.cpp | 14 + examples/ordered_json.output | 5 + examples/ordered_map.cpp | 43 + examples/ordered_map.output | 4 + examples/other_error.cpp | 30 + examples/other_error.output | 2 + examples/out_of_range.cpp | 20 + examples/out_of_range.output | 2 + examples/parse__allow_exceptions.cpp | 36 + examples/parse__allow_exceptions.output | 2 + examples/parse__array__parser_callback_t.cpp | 30 + .../parse__array__parser_callback_t.output | 20 + ...contiguouscontainer__parser_callback_t.cpp | 15 + ...tiguouscontainer__parser_callback_t.output | 6 + .../parse__istream__parser_callback_t.cpp | 58 + .../parse__istream__parser_callback_t.output | 34 + examples/parse__iterator_pair.cpp | 15 + examples/parse__iterator_pair.output | 6 + examples/parse__pointers.cpp | 15 + examples/parse__pointers.output | 6 + examples/parse__string__parser_callback_t.cpp | 49 + .../parse__string__parser_callback_t.output | 34 + examples/parse_error.cpp | 20 + examples/parse_error.output | 3 + examples/patch.cpp | 33 + examples/patch.output | 11 + examples/patch_inplace.cpp | 35 + examples/patch_inplace.output | 13 + examples/push_back.cpp | 25 + examples/push_back.output | 4 + examples/push_back__initializer_list.cpp | 27 + examples/push_back__initializer_list.output | 4 + examples/push_back__object_t__value.cpp | 25 + examples/push_back__object_t__value.output | 4 + examples/rbegin.cpp | 16 + examples/rbegin.output | 1 + examples/rend.cpp | 19 + examples/rend.output | 1 + examples/sax_parse.cpp | 131 + examples/sax_parse.output | 37 + examples/sax_parse__binary.cpp | 114 + examples/sax_parse__binary.output | 3 + examples/size.cpp | 29 + examples/size.output | 9 + examples/std_hash.cpp | 19 + examples/std_hash.output | 8 + examples/std_swap.cpp | 19 + examples/std_swap.output | 2 + examples/string_t.cpp | 10 + examples/string_t.output | 1 + examples/swap__array_t.cpp | 20 + examples/swap__array_t.output | 2 + examples/swap__binary_t.cpp | 20 + examples/swap__binary_t.output | 2 + examples/swap__object_t.cpp | 20 + examples/swap__object_t.output | 2 + examples/swap__reference.cpp | 18 + examples/swap__reference.output | 2 + examples/swap__string_t.cpp | 20 + examples/swap__string_t.output | 2 + examples/to_bjdata.cpp | 64 + examples/to_bjdata.output | 4 + examples/to_bson.cpp | 22 + examples/to_bson.output | 1 + examples/to_cbor.cpp | 22 + examples/to_cbor.output | 1 + examples/to_json.cpp | 32 + examples/to_json.output | 1 + examples/to_msgpack.cpp | 22 + examples/to_msgpack.output | 1 + examples/to_string.cpp | 20 + examples/to_string.output | 3 + examples/to_ubjson.cpp | 64 + examples/to_ubjson.output | 4 + examples/type.cpp | 28 + examples/type.output | 8 + examples/type_error.cpp | 20 + examples/type_error.output | 2 + examples/type_name.cpp | 27 + examples/type_name.output | 8 + examples/unflatten.cpp | 26 + examples/unflatten.output | 18 + examples/update.cpp | 24 + examples/update.output | 17 + examples/update__range.cpp | 24 + examples/update__range.output | 17 + examples/value__json_ptr.cpp | 31 + examples/value__json_ptr.output | 1 + examples/value__keytype.c++17.cpp | 32 + examples/value__keytype.c++17.output | 1 + examples/value__object_t_key_type.cpp | 30 + examples/value__object_t_key_type.output | 1 + features/arbitrary_types/index.html | 162 + features/assertions/index.html | 41 + features/binary_formats/bjdata/index.html | 98 + features/binary_formats/bson/index.html | 49 + features/binary_formats/cbor/index.html | 48 + features/binary_formats/index.html | 1 + .../binary_formats/messagepack/index.html | 48 + features/binary_formats/ubjson/index.html | 93 + features/binary_values/index.html | 146 + features/comments/index.html | 53 + .../element_access/checked_access/index.html | 15 + .../element_access/default_value/index.html | 5 + features/element_access/index.html | 1 + .../unchecked_access/index.html | 22 + features/enum_conversion/index.html | 27 + features/iterators/index.html | 56 + features/json_patch/index.html | 108 + features/json_pointer/index.html | 48 + features/macros/index.html | 1 + features/merge_patch/index.html | 53 + features/namespace/index.html | 4 + features/object_order/index.html | 60 + features/parsing/index.html | 1 + features/parsing/json_lines/index.html | 36 + features/parsing/parse_exceptions/index.html | 66 + features/parsing/parser_callbacks/index.html | 94 + features/parsing/sax_interface/index.html | 29 + features/types/index.html | 39 + features/types/number_handling/index.html | 57 + home/code_of_conduct/index.html | 1 + home/design_goals/index.html | 1 + home/exceptions/index.html | 259 + home/faq/index.html | 29 + home/license/index.html | 1 + home/releases/index.html | 10 + home/sponsors/index.html | 1 + images/callback_events.png | Bin 0 -> 46039 bytes images/json.gif | Bin 0 -> 1644689 bytes images/json_syntax_number.png | Bin 0 -> 37014 bytes images/range-begin-end.svg | 435 ++ images/range-rbegin-rend.svg | 1232 +++ index.html | 1 + integration/cmake/index.html | 49 + integration/conan/CMakeLists.txt | 9 + integration/conan/Conanfile.txt | 5 + integration/conan/example.cpp | 9 + integration/example.cpp | 10 + integration/index.html | 5 + integration/migration_guide/index.html | 57 + integration/package_managers/index.html | 96 + integration/pkg-config/index.html | 3 + integration/vcpkg/CMakeLists.txt | 7 + integration/vcpkg/example.cpp | 9 + search/search_index.json | 1 + sitemap.xml | 1118 +++ sitemap.xml.gz | Bin 0 -> 1642 bytes 702 files changed, 30461 insertions(+) create mode 100644 .nojekyll create mode 100644 404.html create mode 100644 api/adl_serializer/from_json/index.html create mode 100644 api/adl_serializer/index.html create mode 100644 api/adl_serializer/to_json/index.html create mode 100644 api/basic_json/accept/index.html create mode 100644 api/basic_json/array/index.html create mode 100644 api/basic_json/array_t/index.html create mode 100644 api/basic_json/at/index.html create mode 100644 api/basic_json/back/index.html create mode 100644 api/basic_json/basic_json/index.html create mode 100644 api/basic_json/begin/index.html create mode 100644 api/basic_json/binary/index.html create mode 100644 api/basic_json/binary_t/index.html create mode 100644 api/basic_json/boolean_t/index.html create mode 100644 api/basic_json/cbegin/index.html create mode 100644 api/basic_json/cbor_tag_handler_t/index.html create mode 100644 api/basic_json/cend/index.html create mode 100644 api/basic_json/clear/index.html create mode 100644 api/basic_json/contains/index.html create mode 100644 api/basic_json/count/index.html create mode 100644 api/basic_json/crbegin/index.html create mode 100644 api/basic_json/crend/index.html create mode 100644 api/basic_json/default_object_comparator_t/index.html create mode 100644 api/basic_json/diff/index.html create mode 100644 api/basic_json/dump/index.html create mode 100644 api/basic_json/emplace/index.html create mode 100644 api/basic_json/emplace_back/index.html create mode 100644 api/basic_json/empty/index.html create mode 100644 api/basic_json/end/index.html create mode 100644 api/basic_json/erase/index.html create mode 100644 api/basic_json/error_handler_t/index.html create mode 100644 api/basic_json/exception/index.html create mode 100644 api/basic_json/find/index.html create mode 100644 api/basic_json/flatten/index.html create mode 100644 api/basic_json/from_bjdata/index.html create mode 100644 api/basic_json/from_bson/index.html create mode 100644 api/basic_json/from_cbor/index.html create mode 100644 api/basic_json/from_msgpack/index.html create mode 100644 api/basic_json/from_ubjson/index.html create mode 100644 api/basic_json/front/index.html create mode 100644 api/basic_json/get/index.html create mode 100644 api/basic_json/get_allocator/index.html create mode 100644 api/basic_json/get_binary/index.html create mode 100644 api/basic_json/get_ptr/index.html create mode 100644 api/basic_json/get_ref/index.html create mode 100644 api/basic_json/get_to/index.html create mode 100644 api/basic_json/index.html create mode 100644 api/basic_json/input_format_t/index.html create mode 100644 api/basic_json/insert/index.html create mode 100644 api/basic_json/invalid_iterator/index.html create mode 100644 api/basic_json/is_array/index.html create mode 100644 api/basic_json/is_binary/index.html create mode 100644 api/basic_json/is_boolean/index.html create mode 100644 api/basic_json/is_discarded/index.html create mode 100644 api/basic_json/is_null/index.html create mode 100644 api/basic_json/is_number/index.html create mode 100644 api/basic_json/is_number_float/index.html create mode 100644 api/basic_json/is_number_integer/index.html create mode 100644 api/basic_json/is_number_unsigned/index.html create mode 100644 api/basic_json/is_object/index.html create mode 100644 api/basic_json/is_primitive/index.html create mode 100644 api/basic_json/is_string/index.html create mode 100644 api/basic_json/is_structured/index.html create mode 100644 api/basic_json/items/index.html create mode 100644 api/basic_json/json_base_class_t/index.html create mode 100644 api/basic_json/json_serializer/index.html create mode 100644 api/basic_json/max_size/index.html create mode 100644 api/basic_json/merge_patch/index.html create mode 100644 api/basic_json/meta/index.html create mode 100644 api/basic_json/number_float_t/index.html create mode 100644 api/basic_json/number_integer_t/index.html create mode 100644 api/basic_json/number_unsigned_t/index.html create mode 100644 api/basic_json/object/index.html create mode 100644 api/basic_json/object_comparator_t/index.html create mode 100644 api/basic_json/object_t/index.html create mode 100644 api/basic_json/operator+=/index.html create mode 100644 api/basic_json/operator=/index.html create mode 100644 api/basic_json/operator[]/index.html create mode 100644 api/basic_json/operator_ValueType/index.html create mode 100644 api/basic_json/operator_eq/index.html create mode 100644 api/basic_json/operator_ge/index.html create mode 100644 api/basic_json/operator_gt/index.html create mode 100644 api/basic_json/operator_gtgt/index.html create mode 100644 api/basic_json/operator_le/index.html create mode 100644 api/basic_json/operator_literal_json/index.html create mode 100644 api/basic_json/operator_literal_json_pointer/index.html create mode 100644 api/basic_json/operator_lt/index.html create mode 100644 api/basic_json/operator_ltlt/index.html create mode 100644 api/basic_json/operator_ne/index.html create mode 100644 api/basic_json/operator_spaceship/index.html create mode 100644 api/basic_json/operator_value_t/index.html create mode 100644 api/basic_json/other_error/index.html create mode 100644 api/basic_json/out_of_range/index.html create mode 100644 api/basic_json/parse/index.html create mode 100644 api/basic_json/parse_error/index.html create mode 100644 api/basic_json/parse_event_t/index.html create mode 100644 api/basic_json/parser_callback_t/index.html create mode 100644 api/basic_json/patch/index.html create mode 100644 api/basic_json/patch_inplace/index.html create mode 100644 api/basic_json/push_back/index.html create mode 100644 api/basic_json/rbegin/index.html create mode 100644 api/basic_json/rend/index.html create mode 100644 api/basic_json/sax_parse/index.html create mode 100644 api/basic_json/size/index.html create mode 100644 api/basic_json/std_hash/index.html create mode 100644 api/basic_json/std_swap/index.html create mode 100644 api/basic_json/string_t/index.html create mode 100644 api/basic_json/swap/index.html create mode 100644 api/basic_json/to_bjdata/index.html create mode 100644 api/basic_json/to_bson/index.html create mode 100644 api/basic_json/to_cbor/index.html create mode 100644 api/basic_json/to_msgpack/index.html create mode 100644 api/basic_json/to_string/index.html create mode 100644 api/basic_json/to_ubjson/index.html create mode 100644 api/basic_json/type/index.html create mode 100644 api/basic_json/type_error/index.html create mode 100644 api/basic_json/type_name/index.html create mode 100644 api/basic_json/unflatten/index.html create mode 100644 api/basic_json/update/index.html create mode 100644 api/basic_json/value/index.html create mode 100644 api/basic_json/value_t/index.html create mode 100644 api/basic_json/~basic_json/index.html create mode 100644 api/byte_container_with_subtype/byte_container_with_subtype/index.html create mode 100644 api/byte_container_with_subtype/clear_subtype/index.html create mode 100644 api/byte_container_with_subtype/has_subtype/index.html create mode 100644 api/byte_container_with_subtype/index.html create mode 100644 api/byte_container_with_subtype/set_subtype/index.html create mode 100644 api/byte_container_with_subtype/subtype/index.html create mode 100644 api/json/index.html create mode 100644 api/json_pointer/back/index.html create mode 100644 api/json_pointer/empty/index.html create mode 100644 api/json_pointer/index.html create mode 100644 api/json_pointer/json_pointer/index.html create mode 100644 api/json_pointer/operator_eq/index.html create mode 100644 api/json_pointer/operator_ne/index.html create mode 100644 api/json_pointer/operator_slash/index.html create mode 100644 api/json_pointer/operator_slasheq/index.html create mode 100644 api/json_pointer/operator_string/index.html create mode 100644 api/json_pointer/operator_string_t/index.html create mode 100644 api/json_pointer/parent_pointer/index.html create mode 100644 api/json_pointer/pop_back/index.html create mode 100644 api/json_pointer/push_back/index.html create mode 100644 api/json_pointer/string_t/index.html create mode 100644 api/json_pointer/to_string/index.html create mode 100644 api/json_sax/binary/index.html create mode 100644 api/json_sax/boolean/index.html create mode 100644 api/json_sax/end_array/index.html create mode 100644 api/json_sax/end_object/index.html create mode 100644 api/json_sax/index.html create mode 100644 api/json_sax/key/index.html create mode 100644 api/json_sax/null/index.html create mode 100644 api/json_sax/number_float/index.html create mode 100644 api/json_sax/number_integer/index.html create mode 100644 api/json_sax/number_unsigned/index.html create mode 100644 api/json_sax/parse_error/index.html create mode 100644 api/json_sax/start_array/index.html create mode 100644 api/json_sax/start_object/index.html create mode 100644 api/json_sax/string/index.html create mode 100644 api/macros/index.html create mode 100644 api/macros/json_assert/index.html create mode 100644 api/macros/json_diagnostics/index.html create mode 100644 api/macros/json_disable_enum_serialization/index.html create mode 100644 api/macros/json_has_cpp_11/index.html create mode 100644 api/macros/json_has_filesystem/index.html create mode 100644 api/macros/json_has_ranges/index.html create mode 100644 api/macros/json_has_three_way_comparison/index.html create mode 100644 api/macros/json_no_io/index.html create mode 100644 api/macros/json_noexception/index.html create mode 100644 api/macros/json_skip_library_version_check/index.html create mode 100644 api/macros/json_skip_unsupported_compiler_check/index.html create mode 100644 api/macros/json_throw_user/index.html create mode 100644 api/macros/json_use_global_udls/index.html create mode 100644 api/macros/json_use_implicit_conversions/index.html create mode 100644 api/macros/json_use_legacy_discarded_value_comparison/index.html create mode 100644 api/macros/nlohmann_define_type_intrusive/index.html create mode 100644 api/macros/nlohmann_define_type_non_intrusive/index.html create mode 100644 api/macros/nlohmann_json_namespace/index.html create mode 100644 api/macros/nlohmann_json_namespace_begin/index.html create mode 100644 api/macros/nlohmann_json_namespace_no_version/index.html create mode 100644 api/macros/nlohmann_json_serialize_enum/index.html create mode 100644 api/macros/nlohmann_json_version_major/index.html create mode 100644 api/operator_gtgt/index.html create mode 100644 api/operator_literal_json/index.html create mode 100644 api/operator_literal_json_pointer/index.html create mode 100644 api/operator_ltlt/index.html create mode 100644 api/ordered_json/index.html create mode 100644 api/ordered_map/index.html create mode 100644 assets/images/favicon.png create mode 100644 assets/javascripts/bundle.5a2dcb6a.min.js create mode 100644 assets/javascripts/bundle.5a2dcb6a.min.js.map create mode 100644 assets/javascripts/extra/bundle.5f09fbc3.min.js create mode 100644 assets/javascripts/extra/bundle.5f09fbc3.min.js.map create mode 100644 assets/javascripts/lunr/min/lunr.ar.min.js create mode 100644 assets/javascripts/lunr/min/lunr.da.min.js create mode 100644 assets/javascripts/lunr/min/lunr.de.min.js create mode 100644 assets/javascripts/lunr/min/lunr.du.min.js create mode 100644 assets/javascripts/lunr/min/lunr.es.min.js create mode 100644 assets/javascripts/lunr/min/lunr.fi.min.js create mode 100644 assets/javascripts/lunr/min/lunr.fr.min.js create mode 100644 assets/javascripts/lunr/min/lunr.hi.min.js create mode 100644 assets/javascripts/lunr/min/lunr.hu.min.js create mode 100644 assets/javascripts/lunr/min/lunr.it.min.js create mode 100644 assets/javascripts/lunr/min/lunr.ja.min.js create mode 100644 assets/javascripts/lunr/min/lunr.jp.min.js create mode 100644 assets/javascripts/lunr/min/lunr.ko.min.js create mode 100644 assets/javascripts/lunr/min/lunr.multi.min.js create mode 100644 assets/javascripts/lunr/min/lunr.nl.min.js create mode 100644 assets/javascripts/lunr/min/lunr.no.min.js create mode 100644 assets/javascripts/lunr/min/lunr.pt.min.js create mode 100644 assets/javascripts/lunr/min/lunr.ro.min.js create mode 100644 assets/javascripts/lunr/min/lunr.ru.min.js create mode 100644 assets/javascripts/lunr/min/lunr.stemmer.support.min.js create mode 100644 assets/javascripts/lunr/min/lunr.sv.min.js create mode 100644 assets/javascripts/lunr/min/lunr.ta.min.js create mode 100644 assets/javascripts/lunr/min/lunr.th.min.js create mode 100644 assets/javascripts/lunr/min/lunr.tr.min.js create mode 100644 assets/javascripts/lunr/min/lunr.vi.min.js create mode 100644 assets/javascripts/lunr/min/lunr.zh.min.js create mode 100644 assets/javascripts/lunr/tinyseg.js create mode 100644 assets/javascripts/lunr/wordcut.js create mode 100644 assets/javascripts/workers/search.16e2a7d4.min.js create mode 100644 assets/javascripts/workers/search.16e2a7d4.min.js.map create mode 100644 assets/stylesheets/extra.0d2c79a8.min.css create mode 100644 assets/stylesheets/extra.0d2c79a8.min.css.map create mode 100644 assets/stylesheets/main.975780f9.min.css create mode 100644 assets/stylesheets/main.975780f9.min.css.map create mode 100644 assets/stylesheets/palette.2505c338.min.css create mode 100644 assets/stylesheets/palette.2505c338.min.css.map create mode 100644 css/custom.css create mode 100644 examples/README.cpp create mode 100644 examples/README.output create mode 100644 examples/accept__string.cpp create mode 100644 examples/accept__string.output create mode 100644 examples/array.cpp create mode 100644 examples/array.output create mode 100644 examples/array_t.cpp create mode 100644 examples/array_t.output create mode 100644 examples/at__json_pointer.cpp create mode 100644 examples/at__json_pointer.output create mode 100644 examples/at__json_pointer_const.cpp create mode 100644 examples/at__json_pointer_const.output create mode 100644 examples/at__keytype.c++17.cpp create mode 100644 examples/at__keytype.c++17.output create mode 100644 examples/at__keytype_const.c++17.cpp create mode 100644 examples/at__keytype_const.c++17.output create mode 100644 examples/at__object_t_key_type.cpp create mode 100644 examples/at__object_t_key_type.output create mode 100644 examples/at__object_t_key_type_const.cpp create mode 100644 examples/at__object_t_key_type_const.output create mode 100644 examples/at__size_type.cpp create mode 100644 examples/at__size_type.output create mode 100644 examples/at__size_type_const.cpp create mode 100644 examples/at__size_type_const.output create mode 100644 examples/back.cpp create mode 100644 examples/back.output create mode 100644 examples/basic_json__CompatibleType.cpp create mode 100644 examples/basic_json__CompatibleType.output create mode 100644 examples/basic_json__InputIt_InputIt.cpp create mode 100644 examples/basic_json__InputIt_InputIt.output create mode 100644 examples/basic_json__basic_json.cpp create mode 100644 examples/basic_json__basic_json.output create mode 100644 examples/basic_json__copyassignment.cpp create mode 100644 examples/basic_json__copyassignment.output create mode 100644 examples/basic_json__list_init_t.cpp create mode 100644 examples/basic_json__list_init_t.output create mode 100644 examples/basic_json__moveconstructor.cpp create mode 100644 examples/basic_json__moveconstructor.output create mode 100644 examples/basic_json__nullptr_t.cpp create mode 100644 examples/basic_json__nullptr_t.output create mode 100644 examples/basic_json__size_type_basic_json.cpp create mode 100644 examples/basic_json__size_type_basic_json.output create mode 100644 examples/basic_json__value_t.cpp create mode 100644 examples/basic_json__value_t.output create mode 100644 examples/begin.cpp create mode 100644 examples/begin.output create mode 100644 examples/binary.cpp create mode 100644 examples/binary.output create mode 100644 examples/binary_t.cpp create mode 100644 examples/binary_t.output create mode 100644 examples/boolean_t.cpp create mode 100644 examples/boolean_t.output create mode 100644 examples/byte_container_with_subtype__byte_container_with_subtype.cpp create mode 100644 examples/byte_container_with_subtype__byte_container_with_subtype.output create mode 100644 examples/byte_container_with_subtype__clear_subtype.cpp create mode 100644 examples/byte_container_with_subtype__clear_subtype.output create mode 100644 examples/byte_container_with_subtype__has_subtype.cpp create mode 100644 examples/byte_container_with_subtype__has_subtype.output create mode 100644 examples/byte_container_with_subtype__set_subtype.cpp create mode 100644 examples/byte_container_with_subtype__set_subtype.output create mode 100644 examples/byte_container_with_subtype__subtype.cpp create mode 100644 examples/byte_container_with_subtype__subtype.output create mode 100644 examples/cbegin.cpp create mode 100644 examples/cbegin.output create mode 100644 examples/cbor_tag_handler_t.cpp create mode 100644 examples/cbor_tag_handler_t.output create mode 100644 examples/cend.cpp create mode 100644 examples/cend.output create mode 100644 examples/clear.cpp create mode 100644 examples/clear.output create mode 100644 examples/contains__json_pointer.cpp create mode 100644 examples/contains__json_pointer.output create mode 100644 examples/contains__keytype.c++17.cpp create mode 100644 examples/contains__keytype.c++17.output create mode 100644 examples/contains__object_t_key_type.cpp create mode 100644 examples/contains__object_t_key_type.output create mode 100644 examples/count__keytype.c++17.cpp create mode 100644 examples/count__keytype.c++17.output create mode 100644 examples/count__object_t_key_type.cpp create mode 100644 examples/count__object_t_key_type.output create mode 100644 examples/crbegin.cpp create mode 100644 examples/crbegin.output create mode 100644 examples/crend.cpp create mode 100644 examples/crend.output create mode 100644 examples/default_object_comparator_t.cpp create mode 100644 examples/default_object_comparator_t.output create mode 100644 examples/diagnostics_extended.cpp create mode 100644 examples/diagnostics_extended.output create mode 100644 examples/diagnostics_standard.cpp create mode 100644 examples/diagnostics_standard.output create mode 100644 examples/diff.cpp create mode 100644 examples/diff.output create mode 100644 examples/dump.cpp create mode 100644 examples/dump.output create mode 100644 examples/emplace.cpp create mode 100644 examples/emplace.output create mode 100644 examples/emplace_back.cpp create mode 100644 examples/emplace_back.output create mode 100644 examples/empty.cpp create mode 100644 examples/empty.output create mode 100644 examples/end.cpp create mode 100644 examples/end.output create mode 100644 examples/erase__IteratorType.cpp create mode 100644 examples/erase__IteratorType.output create mode 100644 examples/erase__IteratorType_IteratorType.cpp create mode 100644 examples/erase__IteratorType_IteratorType.output create mode 100644 examples/erase__keytype.c++17.cpp create mode 100644 examples/erase__keytype.c++17.output create mode 100644 examples/erase__object_t_key_type.cpp create mode 100644 examples/erase__object_t_key_type.output create mode 100644 examples/erase__size_type.cpp create mode 100644 examples/erase__size_type.output create mode 100644 examples/error_handler_t.cpp create mode 100644 examples/error_handler_t.output create mode 100644 examples/exception.cpp create mode 100644 examples/exception.output create mode 100644 examples/find__keytype.c++17.cpp create mode 100644 examples/find__keytype.c++17.output create mode 100644 examples/find__object_t_key_type.cpp create mode 100644 examples/find__object_t_key_type.output create mode 100644 examples/flatten.cpp create mode 100644 examples/flatten.output create mode 100644 examples/from_bjdata.cpp create mode 100644 examples/from_bjdata.output create mode 100644 examples/from_bson.cpp create mode 100644 examples/from_bson.output create mode 100644 examples/from_cbor.cpp create mode 100644 examples/from_cbor.output create mode 100644 examples/from_json__default_constructible.cpp create mode 100644 examples/from_json__default_constructible.output create mode 100644 examples/from_json__non_default_constructible.cpp create mode 100644 examples/from_json__non_default_constructible.output create mode 100644 examples/from_msgpack.cpp create mode 100644 examples/from_msgpack.output create mode 100644 examples/from_ubjson.cpp create mode 100644 examples/from_ubjson.output create mode 100644 examples/front.cpp create mode 100644 examples/front.output create mode 100644 examples/get__PointerType.cpp create mode 100644 examples/get__PointerType.output create mode 100644 examples/get__ValueType_const.cpp create mode 100644 examples/get__ValueType_const.output create mode 100644 examples/get_allocator.cpp create mode 100644 examples/get_allocator.output create mode 100644 examples/get_binary.cpp create mode 100644 examples/get_binary.output create mode 100644 examples/get_ptr.cpp create mode 100644 examples/get_ptr.output create mode 100644 examples/get_ref.cpp create mode 100644 examples/get_ref.output create mode 100644 examples/get_to.cpp create mode 100644 examples/get_to.output create mode 100644 examples/insert.cpp create mode 100644 examples/insert.output create mode 100644 examples/insert__count.cpp create mode 100644 examples/insert__count.output create mode 100644 examples/insert__ilist.cpp create mode 100644 examples/insert__ilist.output create mode 100644 examples/insert__range.cpp create mode 100644 examples/insert__range.output create mode 100644 examples/insert__range_object.cpp create mode 100644 examples/insert__range_object.output create mode 100644 examples/invalid_iterator.cpp create mode 100644 examples/invalid_iterator.output create mode 100644 examples/is_array.cpp create mode 100644 examples/is_array.output create mode 100644 examples/is_binary.cpp create mode 100644 examples/is_binary.output create mode 100644 examples/is_boolean.cpp create mode 100644 examples/is_boolean.output create mode 100644 examples/is_discarded.cpp create mode 100644 examples/is_discarded.output create mode 100644 examples/is_null.cpp create mode 100644 examples/is_null.output create mode 100644 examples/is_number.cpp create mode 100644 examples/is_number.output create mode 100644 examples/is_number_float.cpp create mode 100644 examples/is_number_float.output create mode 100644 examples/is_number_integer.cpp create mode 100644 examples/is_number_integer.output create mode 100644 examples/is_number_unsigned.cpp create mode 100644 examples/is_number_unsigned.output create mode 100644 examples/is_object.cpp create mode 100644 examples/is_object.output create mode 100644 examples/is_primitive.cpp create mode 100644 examples/is_primitive.output create mode 100644 examples/is_string.cpp create mode 100644 examples/is_string.output create mode 100644 examples/is_structured.cpp create mode 100644 examples/is_structured.output create mode 100644 examples/items.cpp create mode 100644 examples/items.output create mode 100644 examples/json_base_class_t.cpp create mode 100644 examples/json_base_class_t.output create mode 100644 examples/json_lines.cpp create mode 100644 examples/json_lines.output create mode 100644 examples/json_pointer.cpp create mode 100644 examples/json_pointer.output create mode 100644 examples/json_pointer__back.cpp create mode 100644 examples/json_pointer__back.output create mode 100644 examples/json_pointer__empty.cpp create mode 100644 examples/json_pointer__empty.output create mode 100644 examples/json_pointer__operator__equal.cpp create mode 100644 examples/json_pointer__operator__equal.output create mode 100644 examples/json_pointer__operator__equal_stringtype.cpp create mode 100644 examples/json_pointer__operator__equal_stringtype.output create mode 100644 examples/json_pointer__operator__notequal.cpp create mode 100644 examples/json_pointer__operator__notequal.output create mode 100644 examples/json_pointer__operator__notequal_stringtype.cpp create mode 100644 examples/json_pointer__operator__notequal_stringtype.output create mode 100644 examples/json_pointer__operator_add.cpp create mode 100644 examples/json_pointer__operator_add.output create mode 100644 examples/json_pointer__operator_add_binary.cpp create mode 100644 examples/json_pointer__operator_add_binary.output create mode 100644 examples/json_pointer__operator_string_t.cpp create mode 100644 examples/json_pointer__operator_string_t.output create mode 100644 examples/json_pointer__parent_pointer.cpp create mode 100644 examples/json_pointer__parent_pointer.output create mode 100644 examples/json_pointer__pop_back.cpp create mode 100644 examples/json_pointer__pop_back.output create mode 100644 examples/json_pointer__push_back.cpp create mode 100644 examples/json_pointer__push_back.output create mode 100644 examples/json_pointer__string_t.cpp create mode 100644 examples/json_pointer__string_t.output create mode 100644 examples/json_pointer__to_string.cpp create mode 100644 examples/json_pointer__to_string.output create mode 100644 examples/max_size.cpp create mode 100644 examples/max_size.output create mode 100644 examples/merge_patch.cpp create mode 100644 examples/merge_patch.output create mode 100644 examples/meta.cpp create mode 100644 examples/meta.output create mode 100644 examples/nlohmann_define_type_intrusive_explicit.cpp create mode 100644 examples/nlohmann_define_type_intrusive_explicit.output create mode 100644 examples/nlohmann_define_type_intrusive_macro.cpp create mode 100644 examples/nlohmann_define_type_intrusive_macro.output create mode 100644 examples/nlohmann_define_type_intrusive_with_default_explicit.cpp create mode 100644 examples/nlohmann_define_type_intrusive_with_default_explicit.output create mode 100644 examples/nlohmann_define_type_intrusive_with_default_macro.cpp create mode 100644 examples/nlohmann_define_type_intrusive_with_default_macro.output create mode 100644 examples/nlohmann_define_type_non_intrusive_explicit.cpp create mode 100644 examples/nlohmann_define_type_non_intrusive_explicit.output create mode 100644 examples/nlohmann_define_type_non_intrusive_macro.cpp create mode 100644 examples/nlohmann_define_type_non_intrusive_macro.output create mode 100644 examples/nlohmann_define_type_non_intrusive_with_default_explicit.cpp create mode 100644 examples/nlohmann_define_type_non_intrusive_with_default_explicit.output create mode 100644 examples/nlohmann_define_type_non_intrusive_with_default_macro.cpp create mode 100644 examples/nlohmann_define_type_non_intrusive_with_default_macro.output create mode 100644 examples/nlohmann_json_namespace.cpp create mode 100644 examples/nlohmann_json_namespace.output create mode 100644 examples/nlohmann_json_namespace_begin.c++17.cpp create mode 100644 examples/nlohmann_json_namespace_begin.c++17.output create mode 100644 examples/nlohmann_json_namespace_no_version.cpp create mode 100644 examples/nlohmann_json_namespace_no_version.output create mode 100644 examples/nlohmann_json_serialize_enum.cpp create mode 100644 examples/nlohmann_json_serialize_enum.output create mode 100644 examples/nlohmann_json_serialize_enum_2.cpp create mode 100644 examples/nlohmann_json_serialize_enum_2.output create mode 100644 examples/nlohmann_json_version.cpp create mode 100644 examples/nlohmann_json_version.output create mode 100644 examples/number_float_t.cpp create mode 100644 examples/number_float_t.output create mode 100644 examples/number_integer_t.cpp create mode 100644 examples/number_integer_t.output create mode 100644 examples/number_unsigned_t.cpp create mode 100644 examples/number_unsigned_t.output create mode 100644 examples/object.cpp create mode 100644 examples/object.output create mode 100644 examples/object_comparator_t.cpp create mode 100644 examples/object_comparator_t.output create mode 100644 examples/object_t.cpp create mode 100644 examples/object_t.output create mode 100644 examples/operator__ValueType.cpp create mode 100644 examples/operator__ValueType.output create mode 100644 examples/operator__equal.cpp create mode 100644 examples/operator__equal.output create mode 100644 examples/operator__equal__nullptr_t.cpp create mode 100644 examples/operator__equal__nullptr_t.output create mode 100644 examples/operator__equal__specializations.cpp create mode 100644 examples/operator__equal__specializations.output create mode 100644 examples/operator__greater.cpp create mode 100644 examples/operator__greater.output create mode 100644 examples/operator__greaterequal.cpp create mode 100644 examples/operator__greaterequal.output create mode 100644 examples/operator__less.cpp create mode 100644 examples/operator__less.output create mode 100644 examples/operator__lessequal.cpp create mode 100644 examples/operator__lessequal.output create mode 100644 examples/operator__notequal.cpp create mode 100644 examples/operator__notequal.output create mode 100644 examples/operator__notequal__nullptr_t.cpp create mode 100644 examples/operator__notequal__nullptr_t.output create mode 100644 examples/operator__value_t.cpp create mode 100644 examples/operator__value_t.output create mode 100644 examples/operator_array__json_pointer.cpp create mode 100644 examples/operator_array__json_pointer.output create mode 100644 examples/operator_array__json_pointer_const.cpp create mode 100644 examples/operator_array__json_pointer_const.output create mode 100644 examples/operator_array__keytype.c++17.cpp create mode 100644 examples/operator_array__keytype.c++17.output create mode 100644 examples/operator_array__keytype_const.c++17.cpp create mode 100644 examples/operator_array__keytype_const.c++17.output create mode 100644 examples/operator_array__object_t_key_type.cpp create mode 100644 examples/operator_array__object_t_key_type.output create mode 100644 examples/operator_array__object_t_key_type_const.cpp create mode 100644 examples/operator_array__object_t_key_type_const.output create mode 100644 examples/operator_array__size_type.cpp create mode 100644 examples/operator_array__size_type.output create mode 100644 examples/operator_array__size_type_const.cpp create mode 100644 examples/operator_array__size_type_const.output create mode 100644 examples/operator_deserialize.cpp create mode 100644 examples/operator_deserialize.output create mode 100644 examples/operator_literal_json.cpp create mode 100644 examples/operator_literal_json.output create mode 100644 examples/operator_literal_json_pointer.cpp create mode 100644 examples/operator_literal_json_pointer.output create mode 100644 examples/operator_ltlt__basic_json.cpp create mode 100644 examples/operator_ltlt__basic_json.output create mode 100644 examples/operator_ltlt__json_pointer.cpp create mode 100644 examples/operator_ltlt__json_pointer.output create mode 100644 examples/operator_spaceship__const_reference.c++20.cpp create mode 100644 examples/operator_spaceship__const_reference.c++20.output create mode 100644 examples/operator_spaceship__scalartype.c++20.cpp create mode 100644 examples/operator_spaceship__scalartype.c++20.output create mode 100644 examples/ordered_json.cpp create mode 100644 examples/ordered_json.output create mode 100644 examples/ordered_map.cpp create mode 100644 examples/ordered_map.output create mode 100644 examples/other_error.cpp create mode 100644 examples/other_error.output create mode 100644 examples/out_of_range.cpp create mode 100644 examples/out_of_range.output create mode 100644 examples/parse__allow_exceptions.cpp create mode 100644 examples/parse__allow_exceptions.output create mode 100644 examples/parse__array__parser_callback_t.cpp create mode 100644 examples/parse__array__parser_callback_t.output create mode 100644 examples/parse__contiguouscontainer__parser_callback_t.cpp create mode 100644 examples/parse__contiguouscontainer__parser_callback_t.output create mode 100644 examples/parse__istream__parser_callback_t.cpp create mode 100644 examples/parse__istream__parser_callback_t.output create mode 100644 examples/parse__iterator_pair.cpp create mode 100644 examples/parse__iterator_pair.output create mode 100644 examples/parse__pointers.cpp create mode 100644 examples/parse__pointers.output create mode 100644 examples/parse__string__parser_callback_t.cpp create mode 100644 examples/parse__string__parser_callback_t.output create mode 100644 examples/parse_error.cpp create mode 100644 examples/parse_error.output create mode 100644 examples/patch.cpp create mode 100644 examples/patch.output create mode 100644 examples/patch_inplace.cpp create mode 100644 examples/patch_inplace.output create mode 100644 examples/push_back.cpp create mode 100644 examples/push_back.output create mode 100644 examples/push_back__initializer_list.cpp create mode 100644 examples/push_back__initializer_list.output create mode 100644 examples/push_back__object_t__value.cpp create mode 100644 examples/push_back__object_t__value.output create mode 100644 examples/rbegin.cpp create mode 100644 examples/rbegin.output create mode 100644 examples/rend.cpp create mode 100644 examples/rend.output create mode 100644 examples/sax_parse.cpp create mode 100644 examples/sax_parse.output create mode 100644 examples/sax_parse__binary.cpp create mode 100644 examples/sax_parse__binary.output create mode 100644 examples/size.cpp create mode 100644 examples/size.output create mode 100644 examples/std_hash.cpp create mode 100644 examples/std_hash.output create mode 100644 examples/std_swap.cpp create mode 100644 examples/std_swap.output create mode 100644 examples/string_t.cpp create mode 100644 examples/string_t.output create mode 100644 examples/swap__array_t.cpp create mode 100644 examples/swap__array_t.output create mode 100644 examples/swap__binary_t.cpp create mode 100644 examples/swap__binary_t.output create mode 100644 examples/swap__object_t.cpp create mode 100644 examples/swap__object_t.output create mode 100644 examples/swap__reference.cpp create mode 100644 examples/swap__reference.output create mode 100644 examples/swap__string_t.cpp create mode 100644 examples/swap__string_t.output create mode 100644 examples/to_bjdata.cpp create mode 100644 examples/to_bjdata.output create mode 100644 examples/to_bson.cpp create mode 100644 examples/to_bson.output create mode 100644 examples/to_cbor.cpp create mode 100644 examples/to_cbor.output create mode 100644 examples/to_json.cpp create mode 100644 examples/to_json.output create mode 100644 examples/to_msgpack.cpp create mode 100644 examples/to_msgpack.output create mode 100644 examples/to_string.cpp create mode 100644 examples/to_string.output create mode 100644 examples/to_ubjson.cpp create mode 100644 examples/to_ubjson.output create mode 100644 examples/type.cpp create mode 100644 examples/type.output create mode 100644 examples/type_error.cpp create mode 100644 examples/type_error.output create mode 100644 examples/type_name.cpp create mode 100644 examples/type_name.output create mode 100644 examples/unflatten.cpp create mode 100644 examples/unflatten.output create mode 100644 examples/update.cpp create mode 100644 examples/update.output create mode 100644 examples/update__range.cpp create mode 100644 examples/update__range.output create mode 100644 examples/value__json_ptr.cpp create mode 100644 examples/value__json_ptr.output create mode 100644 examples/value__keytype.c++17.cpp create mode 100644 examples/value__keytype.c++17.output create mode 100644 examples/value__object_t_key_type.cpp create mode 100644 examples/value__object_t_key_type.output create mode 100644 features/arbitrary_types/index.html create mode 100644 features/assertions/index.html create mode 100644 features/binary_formats/bjdata/index.html create mode 100644 features/binary_formats/bson/index.html create mode 100644 features/binary_formats/cbor/index.html create mode 100644 features/binary_formats/index.html create mode 100644 features/binary_formats/messagepack/index.html create mode 100644 features/binary_formats/ubjson/index.html create mode 100644 features/binary_values/index.html create mode 100644 features/comments/index.html create mode 100644 features/element_access/checked_access/index.html create mode 100644 features/element_access/default_value/index.html create mode 100644 features/element_access/index.html create mode 100644 features/element_access/unchecked_access/index.html create mode 100644 features/enum_conversion/index.html create mode 100644 features/iterators/index.html create mode 100644 features/json_patch/index.html create mode 100644 features/json_pointer/index.html create mode 100644 features/macros/index.html create mode 100644 features/merge_patch/index.html create mode 100644 features/namespace/index.html create mode 100644 features/object_order/index.html create mode 100644 features/parsing/index.html create mode 100644 features/parsing/json_lines/index.html create mode 100644 features/parsing/parse_exceptions/index.html create mode 100644 features/parsing/parser_callbacks/index.html create mode 100644 features/parsing/sax_interface/index.html create mode 100644 features/types/index.html create mode 100644 features/types/number_handling/index.html create mode 100644 home/code_of_conduct/index.html create mode 100644 home/design_goals/index.html create mode 100644 home/exceptions/index.html create mode 100644 home/faq/index.html create mode 100644 home/license/index.html create mode 100644 home/releases/index.html create mode 100644 home/sponsors/index.html create mode 100644 images/callback_events.png create mode 100644 images/json.gif create mode 100644 images/json_syntax_number.png create mode 100644 images/range-begin-end.svg create mode 100644 images/range-rbegin-rend.svg create mode 100644 index.html create mode 100644 integration/cmake/index.html create mode 100644 integration/conan/CMakeLists.txt create mode 100644 integration/conan/Conanfile.txt create mode 100644 integration/conan/example.cpp create mode 100644 integration/example.cpp create mode 100644 integration/index.html create mode 100644 integration/migration_guide/index.html create mode 100644 integration/package_managers/index.html create mode 100644 integration/pkg-config/index.html create mode 100644 integration/vcpkg/CMakeLists.txt create mode 100644 integration/vcpkg/example.cpp create mode 100644 search/search_index.json create mode 100644 sitemap.xml create mode 100644 sitemap.xml.gz diff --git a/.nojekyll b/.nojekyll new file mode 100644 index 000000000..e69de29bb diff --git a/404.html b/404.html new file mode 100644 index 000000000..4f2a571f2 --- /dev/null +++ b/404.html @@ -0,0 +1 @@ +
// (1)
+template<typename BasicJsonType, typename TargetType = ValueType>
+static auto from_json(BasicJsonType && j, TargetType& val) noexcept(
+ noexcept(::nlohmann::from_json(std::forward<BasicJsonType>(j), val)))
+-> decltype(::nlohmann::from_json(std::forward<BasicJsonType>(j), val), void())
+
+// (2)
+template<typename BasicJsonType, typename TargetType = ValueType>
+static auto from_json(BasicJsonType && j) noexcept(
+noexcept(::nlohmann::from_json(std::forward<BasicJsonType>(j), detail::identity_tag<TargetType> {})))
+-> decltype(::nlohmann::from_json(std::forward<BasicJsonType>(j), detail::identity_tag<TargetType> {}))
+This function is usually called by the get() function of the basic_json class (either explicitly or via the conversion operators).
j (in)val (out)Copy of the JSON value, converted to ValueType
The example below shows how a from_json function can be implemented for a user-defined type. This function is called by the adl_serializer when get<ns::person>() is called.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+namespace ns
+{
+// a simple struct to model a person
+struct person
+{
+ std::string name;
+ std::string address;
+ int age;
+};
+} // namespace ns
+
+namespace ns
+{
+void from_json(const json& j, person& p)
+{
+ j.at("name").get_to(p.name);
+ j.at("address").get_to(p.address);
+ j.at("age").get_to(p.age);
+}
+} // namespace ns
+
+int main()
+{
+ json j;
+ j["name"] = "Ned Flanders";
+ j["address"] = "744 Evergreen Terrace";
+ j["age"] = 60;
+
+ auto p = j.get<ns::person>();
+
+ std::cout << p.name << " (" << p.age << ") lives in " << p.address << std::endl;
+}
+Output:
Ned Flanders (60) lives in 744 Evergreen Terrace
+The example below shows how a from_json is implemented as part of a specialization of the adl_serializer to realize the conversion of a non-default-constructible type.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+namespace ns
+{
+// a simple struct to model a person (not default constructible)
+struct person
+{
+ person(std::string n, std::string a, int aa)
+ : name(std::move(n)), address(std::move(a)), age(aa)
+ {}
+
+ std::string name;
+ std::string address;
+ int age;
+};
+} // namespace ns
+
+namespace nlohmann
+{
+template <>
+struct adl_serializer<ns::person>
+{
+ static ns::person from_json(const json& j)
+ {
+ return {j.at("name"), j.at("address"), j.at("age")};
+ }
+
+ // Here's the catch! You must provide a to_json method! Otherwise, you
+ // will not be able to convert person to json, since you fully
+ // specialized adl_serializer on that type
+ static void to_json(json& j, ns::person p)
+ {
+ j["name"] = p.name;
+ j["address"] = p.address;
+ j["age"] = p.age;
+ }
+};
+} // namespace nlohmann
+
+int main()
+{
+ json j;
+ j["name"] = "Ned Flanders";
+ j["address"] = "744 Evergreen Terrace";
+ j["age"] = 60;
+
+ auto p = j.get<ns::person>();
+
+ std::cout << p.name << " (" << p.age << ") lives in " << p.address << std::endl;
+}
+Output:
Ned Flanders (60) lives in 744 Evergreen Terrace
+template<typename, typename>
+struct adl_serializer;
+Serializer that uses ADL (Argument-Dependent Lookup) to choose to_json/from_json functions from the types' namespaces.
It is implemented similar to
template<typename ValueType>
+struct adl_serializer {
+ template<typename BasicJsonType>
+ static void to_json(BasicJsonType& j, const T& value) {
+ // calls the "to_json" method in T's namespace
+ }
+
+ template<typename BasicJsonType>
+ static void from_json(const BasicJsonType& j, T& value) {
+ // same thing, but with the "from_json" method
+ }
+};
+template<typename BasicJsonType, typename TargetType = ValueType>
+static auto to_json(BasicJsonType& j, TargetType && val) noexcept(
+ noexcept(::nlohmann::to_json(j, std::forward<TargetType>(val))))
+-> decltype(::nlohmann::to_json(j, std::forward<TargetType>(val)), void())
+This function is usually called by the constructors of the basic_json class.
j (out)val (in)The example below shows how a to_json function can be implemented for a user-defined type. This function is called by the adl_serializer when the constructor basic_json(ns::person) is called.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+namespace ns
+{
+// a simple struct to model a person
+struct person
+{
+ std::string name;
+ std::string address;
+ int age;
+};
+} // namespace ns
+
+namespace ns
+{
+void to_json(json& j, const person& p)
+{
+ j = json{ {"name", p.name}, {"address", p.address}, {"age", p.age} };
+}
+} // namespace ns
+
+int main()
+{
+ ns::person p = {"Ned Flanders", "744 Evergreen Terrace", 60};
+
+ json j = p;
+
+ std::cout << j << std::endl;
+}
+Output:
{"address":"744 Evergreen Terrace","age":60,"name":"Ned Flanders"}
+// (1)
+template<typename InputType>
+static bool accept(InputType&& i,
+ const bool ignore_comments = false);
+
+// (2)
+template<typename IteratorType>
+static bool accept(IteratorType first, IteratorType last,
+ const bool ignore_comments = false);
+Checks whether the input is valid JSON.
Reads from a pair of character iterators
The value_type of the iterator must be an integral type with size of 1, 2 or 4 bytes, which will be interpreted respectively as UTF-8, UTF-16 and UTF-32.
Unlike the parse function, this function neither throws an exception in case of invalid JSON input (i.e., a parse error) nor creates diagnostic information.
InputTypeA compatible input, for instance:
std::istream objectFILE pointer (must not be null)std::stringobj for which begin(obj) and end(obj) produces a valid pair of iterators.IteratorTypea compatible iterator type, for instance.
std::string::iterator or std::vector<std::uint8_t>::iteratorptr and ptr + leni (in)ignore_comments (in)true) or yield a parse error (false); (optional, false by default)first (in)last (in)Whether the input is valid JSON.
Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
Linear in the length of the input. The parser is a predictive LL(1) parser.
(1) A UTF-8 byte order mark is silently ignored.
Runtime assertion
The precondition that a passed FILE pointer must not be null is enforced with a runtime assertion.
The example below demonstrates the accept() function reading from a string.
#include <iostream>
+#include <iomanip>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // a valid JSON text
+ auto valid_text = R"(
+ {
+ "numbers": [1, 2, 3]
+ }
+ )";
+
+ // an invalid JSON text
+ auto invalid_text = R"(
+ {
+ "strings": ["extra", "comma", ]
+ }
+ )";
+
+ std::cout << std::boolalpha
+ << json::accept(valid_text) << ' '
+ << json::accept(invalid_text) << '\n';
+}
+Output:
true false
+ignore_comments added in version 3.9.0.Deprecation
Overload (2) replaces calls to accept with a pair of iterators as their first parameter which has been deprecated in version 3.8.0. This overload will be removed in version 4.0.0. Please replace all calls like accept({ptr, ptr+len}, ...); with accept(ptr, ptr+len, ...);.
You should be warned by your compiler with a -Wdeprecated-declarations warning if you are using a deprecated function.
static basic_json array(initializer_list_t init = {});
+Creates a JSON array value from a given initializer list. That is, given a list of values a, b, c, creates the JSON value [a, b, c]. If the initializer list is empty, the empty array [] is created.
init (in)JSON array value
Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
Linear in the size of init.
This function is only needed to express two edge cases that cannot be realized with the initializer list constructor (basic_json(initializer_list_t, bool, value_t)). These cases are:
The following code shows an example for the array function.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create JSON arrays
+ json j_no_init_list = json::array();
+ json j_empty_init_list = json::array({});
+ json j_nonempty_init_list = json::array({1, 2, 3, 4});
+ json j_list_of_pairs = json::array({ {"one", 1}, {"two", 2} });
+
+ // serialize the JSON arrays
+ std::cout << j_no_init_list << '\n';
+ std::cout << j_empty_init_list << '\n';
+ std::cout << j_nonempty_init_list << '\n';
+ std::cout << j_list_of_pairs << '\n';
+}
+Output:
[]
+[]
+[1,2,3,4]
+[["one",1],["two",2]]
+basic_json(initializer_list_t) - create a JSON value from an initializer listobject - create a JSON object value from an initializer listusing array_t = ArrayType<basic_json, AllocatorType<basic_json>>;
+The type used to store JSON arrays.
RFC 8259 describes JSON arrays as follows:
An array is an ordered sequence of zero or more values.
To store objects in C++, a type is defined by the template parameters explained below.
ArrayTypestd::vector or std::list)AllocatorTypestd::allocator)With the default values for ArrayType (std::vector) and AllocatorType (std::allocator), the default value for array_t is:
std::vector<
+ basic_json, // value_type
+ std::allocator<basic_json> // allocator_type
+>
+RFC 8259 specifies:
An implementation may set limits on the maximum depth of nesting.
In this class, the array's limit of nesting is not explicitly constrained. However, a maximum depth of nesting may be introduced by the compiler or runtime environment. A theoretical limit can be queried by calling the max_size function of a JSON array.
Arrays are stored as pointers in a basic_json type. That is, for any access to array values, a pointer of type array_t* must be dereferenced.
The following code shows that array_t is by default, a typedef to std::vector<nlohmann::json>.
#include <iostream>
+#include <iomanip>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ std::cout << std::boolalpha << std::is_same<std::vector<json>, json::array_t>::value << std::endl;
+}
+Output:
true
+// (1)
+reference at(size_type idx);
+const_reference at(size_type idx) const;
+
+// (2)
+reference at(const typename object_t::key_type& key);
+const_reference at(const typename object_t::key_type& key) const;
+
+// (3)
+template<typename KeyType>
+reference at(KeyType&& key);
+template<typename KeyType>
+const_reference at(KeyType&& key) const;
+
+// (4)
+reference at(const json_pointer& ptr);
+const_reference at(const json_pointer& ptr) const;
+idx, with bounds checking.key, with bounds checking.KeyType is comparable with typename object_t::key_type and typename object_comparator_t::is_transparent denotes a type.ptr, with bounds checking.KeyTypejson_pointer that is comparable with string_t using object_comparator_t. This can also be a string view (C++17).idx (in)key (in)ptr (in)idxkeykeyptrStrong exception safety: if an exception occurs, the original value stays intact.
type_error.304 if the JSON value is not an array; in this case, calling at with an index makes no sense. See example below.out_of_range.401 if the index idx is out of range of the array; that is, idx >= size(). See example below.type_error.304 if the JSON value is not an object; in this case, calling at with a key makes no sense. See example below.out_of_range.403 if the key key is not stored in the object; that is, find(key) == end(). See example below.parse_error.106 if an array index in the passed JSON pointer ptr begins with '0'. See example below.parse_error.109 if an array index in the passed JSON pointer ptr is not a number. See example below.out_of_range.401 if an array index in the passed JSON pointer ptr is out of range. See example below.out_of_range.402 if the array index '-' is used in the passed JSON pointer ptr. As at provides checked access (and no elements are implicitly inserted), the index '-' is always invalid. See example below.out_of_range.403 if the JSON pointer describes a key of an object which cannot be found. See example below.out_of_range.404 if the JSON pointer ptr can not be resolved. See example below.The example below shows how array elements can be read and written using at(). It also demonstrates the different exceptions that can be thrown.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create JSON array
+ json array = {"first", "2nd", "third", "fourth"};
+
+ // output element at index 2 (third element)
+ std::cout << array.at(2) << '\n';
+
+ // change element at index 1 (second element) to "second"
+ array.at(1) = "second";
+
+ // output changed array
+ std::cout << array << '\n';
+
+
+ // exception type_error.304
+ try
+ {
+ // use at() on a non-array type
+ json str = "I am a string";
+ str.at(0) = "Another string";
+ }
+ catch (json::type_error& e)
+ {
+ std::cout << e.what() << '\n';
+ }
+
+ // exception out_of_range.401
+ try
+ {
+ // try to write beyond the array limit
+ array.at(5) = "sixth";
+ }
+ catch (json::out_of_range& e)
+ {
+ std::cout << e.what() << '\n';
+ }
+}
+Output:
"third"
+["first","second","third","fourth"]
+[json.exception.type_error.304] cannot use at() with string
+[json.exception.out_of_range.401] array index 5 is out of range
+The example below shows how array elements can be read using at(). It also demonstrates the different exceptions that can be thrown.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create JSON array
+ const json array = {"first", "2nd", "third", "fourth"};
+
+ // output element at index 2 (third element)
+ std::cout << array.at(2) << '\n';
+
+
+ // exception type_error.304
+ try
+ {
+ // use at() on a non-array type
+ const json str = "I am a string";
+ std::cout << str.at(0) << '\n';
+ }
+ catch (json::type_error& e)
+ {
+ std::cout << e.what() << '\n';
+ }
+
+ // exception out_of_range.401
+ try
+ {
+ // try to read beyond the array limit
+ std::cout << array.at(5) << '\n';
+ }
+ catch (json::out_of_range& e)
+ {
+ std::cout << e.what() << '\n';
+ }
+}
+Output:
"third"
+[json.exception.type_error.304] cannot use at() with string
+[json.exception.out_of_range.401] array index 5 is out of range
+The example below shows how object elements can be read and written using at(). It also demonstrates the different exceptions that can be thrown.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create JSON object
+ json object =
+ {
+ {"the good", "il buono"},
+ {"the bad", "il cattivo"},
+ {"the ugly", "il brutto"}
+ };
+
+ // output element with key "the ugly"
+ std::cout << object.at("the ugly") << '\n';
+
+ // change element with key "the bad"
+ object.at("the bad") = "il cattivo";
+
+ // output changed array
+ std::cout << object << '\n';
+
+
+ // exception type_error.304
+ try
+ {
+ // use at() on a non-object type
+ json str = "I am a string";
+ str.at("the good") = "Another string";
+ }
+ catch (json::type_error& e)
+ {
+ std::cout << e.what() << '\n';
+ }
+
+ // exception out_of_range.401
+ try
+ {
+ // try to write at a nonexisting key
+ object.at("the fast") = "il rapido";
+ }
+ catch (json::out_of_range& e)
+ {
+ std::cout << e.what() << '\n';
+ }
+}
+Output:
"il brutto"
+{"the bad":"il cattivo","the good":"il buono","the ugly":"il brutto"}
+[json.exception.type_error.304] cannot use at() with string
+[json.exception.out_of_range.403] key 'the fast' not found
+The example below shows how object elements can be read using at(). It also demonstrates the different exceptions that can be thrown.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create JSON object
+ const json object =
+ {
+ {"the good", "il buono"},
+ {"the bad", "il cattivo"},
+ {"the ugly", "il brutto"}
+ };
+
+ // output element with key "the ugly"
+ std::cout << object.at("the ugly") << '\n';
+
+
+ // exception type_error.304
+ try
+ {
+ // use at() on a non-object type
+ const json str = "I am a string";
+ std::cout << str.at("the good") << '\n';
+ }
+ catch (json::type_error& e)
+ {
+ std::cout << e.what() << '\n';
+ }
+
+ // exception out_of_range.401
+ try
+ {
+ // try to read from a nonexisting key
+ std::cout << object.at("the fast") << '\n';
+ }
+ catch (json::out_of_range)
+ {
+ std::cout << "out of range" << '\n';
+ }
+}
+Output:
"il brutto"
+[json.exception.type_error.304] cannot use at() with string
+out of range
+The example below shows how object elements can be read and written using at(). It also demonstrates the different exceptions that can be thrown.
#include <iostream>
+#include <string_view>
+#include <nlohmann/json.hpp>
+
+using namespace std::string_view_literals;
+using json = nlohmann::json;
+
+int main()
+{
+ // create JSON object
+ json object =
+ {
+ {"the good", "il buono"},
+ {"the bad", "il cattivo"},
+ {"the ugly", "il brutto"}
+ };
+
+ // output element with key "the ugly" using string_view
+ std::cout << object.at("the ugly"sv) << '\n';
+
+ // change element with key "the bad" using string_view
+ object.at("the bad"sv) = "il cattivo";
+
+ // output changed array
+ std::cout << object << '\n';
+
+
+ // exception type_error.304
+ try
+ {
+ // use at() with string_view on a non-object type
+ json str = "I am a string";
+ str.at("the good"sv) = "Another string";
+ }
+ catch (json::type_error& e)
+ {
+ std::cout << e.what() << '\n';
+ }
+
+ // exception out_of_range.401
+ try
+ {
+ // try to write at a nonexisting key using string_view
+ object.at("the fast"sv) = "il rapido";
+ }
+ catch (json::out_of_range& e)
+ {
+ std::cout << e.what() << '\n';
+ }
+}
+Output:
"il brutto"
+{"the bad":"il cattivo","the good":"il buono","the ugly":"il brutto"}
+[json.exception.type_error.304] cannot use at() with string
+[json.exception.out_of_range.403] key 'the fast' not found
+The example below shows how object elements can be read using at(). It also demonstrates the different exceptions that can be thrown.
#include <iostream>
+#include <string_view>
+#include <nlohmann/json.hpp>
+
+using namespace std::string_view_literals;
+using json = nlohmann::json;
+
+int main()
+{
+ // create JSON object
+ const json object =
+ {
+ {"the good", "il buono"},
+ {"the bad", "il cattivo"},
+ {"the ugly", "il brutto"}
+ };
+
+ // output element with key "the ugly" using string_view
+ std::cout << object.at("the ugly"sv) << '\n';
+
+
+ // exception type_error.304
+ try
+ {
+ // use at() with string_view on a non-object type
+ const json str = "I am a string";
+ std::cout << str.at("the good"sv) << '\n';
+ }
+ catch (json::type_error& e)
+ {
+ std::cout << e.what() << '\n';
+ }
+
+ // exception out_of_range.401
+ try
+ {
+ // try to read from a nonexisting key using string_view
+ std::cout << object.at("the fast"sv) << '\n';
+ }
+ catch (json::out_of_range)
+ {
+ std::cout << "out of range" << '\n';
+ }
+}
+Output:
"il brutto"
+[json.exception.type_error.304] cannot use at() with string
+out of range
+The example below shows how object elements can be read and written using at(). It also demonstrates the different exceptions that can be thrown.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+using namespace nlohmann::literals;
+
+int main()
+{
+ // create a JSON value
+ json j =
+ {
+ {"number", 1}, {"string", "foo"}, {"array", {1, 2}}
+ };
+
+ // read-only access
+
+ // output element with JSON pointer "/number"
+ std::cout << j.at("/number"_json_pointer) << '\n';
+ // output element with JSON pointer "/string"
+ std::cout << j.at("/string"_json_pointer) << '\n';
+ // output element with JSON pointer "/array"
+ std::cout << j.at("/array"_json_pointer) << '\n';
+ // output element with JSON pointer "/array/1"
+ std::cout << j.at("/array/1"_json_pointer) << '\n';
+
+ // writing access
+
+ // change the string
+ j.at("/string"_json_pointer) = "bar";
+ // output the changed string
+ std::cout << j["string"] << '\n';
+
+ // change an array element
+ j.at("/array/1"_json_pointer) = 21;
+ // output the changed array
+ std::cout << j["array"] << '\n';
+
+
+ // out_of_range.106
+ try
+ {
+ // try to use an array index with leading '0'
+ json::reference ref = j.at("/array/01"_json_pointer);
+ }
+ catch (json::parse_error& e)
+ {
+ std::cout << e.what() << '\n';
+ }
+
+ // out_of_range.109
+ try
+ {
+ // try to use an array index that is not a number
+ json::reference ref = j.at("/array/one"_json_pointer);
+ }
+ catch (json::parse_error& e)
+ {
+ std::cout << e.what() << '\n';
+ }
+
+ // out_of_range.401
+ try
+ {
+ // try to use an invalid array index
+ json::reference ref = j.at("/array/4"_json_pointer);
+ }
+ catch (json::out_of_range& e)
+ {
+ std::cout << e.what() << '\n';
+ }
+
+ // out_of_range.402
+ try
+ {
+ // try to use the array index '-'
+ json::reference ref = j.at("/array/-"_json_pointer);
+ }
+ catch (json::out_of_range& e)
+ {
+ std::cout << e.what() << '\n';
+ }
+
+ // out_of_range.403
+ try
+ {
+ // try to use a JSON pointer to a nonexistent object key
+ json::const_reference ref = j.at("/foo"_json_pointer);
+ }
+ catch (json::out_of_range& e)
+ {
+ std::cout << e.what() << '\n';
+ }
+
+ // out_of_range.404
+ try
+ {
+ // try to use a JSON pointer that cannot be resolved
+ json::reference ref = j.at("/number/foo"_json_pointer);
+ }
+ catch (json::out_of_range& e)
+ {
+ std::cout << e.what() << '\n';
+ }
+}
+Output:
1
+"foo"
+[1,2]
+2
+"bar"
+[1,21]
+[json.exception.parse_error.106] parse error: array index '01' must not begin with '0'
+[json.exception.parse_error.109] parse error: array index 'one' is not a number
+[json.exception.out_of_range.401] array index 4 is out of range
+[json.exception.out_of_range.402] array index '-' (2) is out of range
+[json.exception.out_of_range.403] key 'foo' not found
+[json.exception.out_of_range.404] unresolved reference token 'foo'
+The example below shows how object elements can be read using at(). It also demonstrates the different exceptions that can be thrown.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+using namespace nlohmann::literals;
+
+int main()
+{
+ // create a JSON value
+ const json j =
+ {
+ {"number", 1}, {"string", "foo"}, {"array", {1, 2}}
+ };
+
+ // read-only access
+
+ // output element with JSON pointer "/number"
+ std::cout << j.at("/number"_json_pointer) << '\n';
+ // output element with JSON pointer "/string"
+ std::cout << j.at("/string"_json_pointer) << '\n';
+ // output element with JSON pointer "/array"
+ std::cout << j.at("/array"_json_pointer) << '\n';
+ // output element with JSON pointer "/array/1"
+ std::cout << j.at("/array/1"_json_pointer) << '\n';
+
+ // out_of_range.109
+ try
+ {
+ // try to use an array index that is not a number
+ json::const_reference ref = j.at("/array/one"_json_pointer);
+ }
+ catch (json::parse_error& e)
+ {
+ std::cout << e.what() << '\n';
+ }
+
+ // out_of_range.401
+ try
+ {
+ // try to use an invalid array index
+ json::const_reference ref = j.at("/array/4"_json_pointer);
+ }
+ catch (json::out_of_range& e)
+ {
+ std::cout << e.what() << '\n';
+ }
+
+ // out_of_range.402
+ try
+ {
+ // try to use the array index '-'
+ json::const_reference ref = j.at("/array/-"_json_pointer);
+ }
+ catch (json::out_of_range& e)
+ {
+ std::cout << e.what() << '\n';
+ }
+
+ // out_of_range.403
+ try
+ {
+ // try to use a JSON pointer to a nonexistent object key
+ json::const_reference ref = j.at("/foo"_json_pointer);
+ }
+ catch (json::out_of_range& e)
+ {
+ std::cout << e.what() << '\n';
+ }
+
+ // out_of_range.404
+ try
+ {
+ // try to use a JSON pointer that cannot be resolved
+ json::const_reference ref = j.at("/number/foo"_json_pointer);
+ }
+ catch (json::out_of_range& e)
+ {
+ std::cout << e.what() << '\n';
+ }
+}
+Output:
1
+"foo"
+[1,2]
+2
+[json.exception.parse_error.109] parse error: array index 'one' is not a number
+[json.exception.out_of_range.401] array index 4 is out of range
+[json.exception.out_of_range.402] array index '-' (2) is out of range
+[json.exception.out_of_range.403] key 'foo' not found
+[json.exception.out_of_range.404] unresolved reference token 'foo'
+operator[] for unchecked access by referencevalue for access with default valuereference back();
+
+const_reference back() const;
+Returns a reference to the last element in the container. For a JSON container c, the expression c.back() is equivalent to
auto tmp = c.end();
+--tmp;
+return *tmp;
+In case of a structured type (array or object), a reference to the last element is returned. In case of number, string, boolean, or binary values, a reference to the value is returned.
Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
If the JSON value is null, exception invalid_iterator.214 is thrown.
Constant.
Precondition
The array or object must not be empty. Calling back on an empty array or object yields undefined behavior.
The following code shows an example for back().
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create JSON values
+ json j_boolean = true;
+ json j_number_integer = 17;
+ json j_number_float = 23.42;
+ json j_object = {{"one", 1}, {"two", 2}};
+ json j_object_empty(json::value_t::object);
+ json j_array = {1, 2, 4, 8, 16};
+ json j_array_empty(json::value_t::array);
+ json j_string = "Hello, world";
+
+ // call back()
+ std::cout << j_boolean.back() << '\n';
+ std::cout << j_number_integer.back() << '\n';
+ std::cout << j_number_float.back() << '\n';
+ std::cout << j_object.back() << '\n';
+ //std::cout << j_object_empty.back() << '\n'; // undefined behavior
+ std::cout << j_array.back() << '\n';
+ //std::cout << j_array_empty.back() << '\n'; // undefined behavior
+ std::cout << j_string.back() << '\n';
+
+ // back() called on a null value
+ try
+ {
+ json j_null;
+ j_null.back();
+ }
+ catch (json::invalid_iterator& e)
+ {
+ std::cout << e.what() << '\n';
+ }
+}
+Output:
true
+17
+23.42
+2
+16
+"Hello, world"
+[json.exception.invalid_iterator.214] cannot get value
+// (1)
+basic_json(const value_t v);
+
+// (2)
+basic_json(std::nullptr_t = nullptr) noexcept;
+
+// (3)
+template<typename CompatibleType>
+basic_json(CompatibleType&& val) noexcept(noexcept(
+ JSONSerializer<U>::to_json(std::declval<basic_json_t&>(),
+ std::forward<CompatibleType>(val))));
+
+// (4)
+template<typename BasicJsonType>
+basic_json(const BasicJsonType& val);
+
+// (5)
+basic_json(initializer_list_t init,
+ bool type_deduction = true,
+ value_t manual_type = value_t::array);
+
+// (6)
+basic_json(size_type cnt, const basic_json& val);
+
+// (7)
+basic_json(iterator first, iterator last);
+basic_json(const_iterator first, const_iterator last);
+
+// (8)
+basic_json(const basic_json& other);
+
+// (9)
+basic_json(basic_json&& other) noexcept;
+Create an empty JSON value with a given type. The value will be default initialized with an empty value which depends on the type:
| Value type | initial value |
|---|---|
| null | null |
| boolean | false |
| string | "" |
| number | 0 |
| object | {} |
| array | [] |
| binary | empty array |
The postcondition of this constructor can be restored by calling clear().
Create a null JSON value. It either takes a null pointer as parameter (explicitly creating null) or no parameter (implicitly creating null). The passed null pointer itself is not read -- it is only used to choose the right constructor.
This is a "catch all" constructor for all compatible JSON types; that is, types for which a to_json() method exists. The constructor forwards the parameter val to that method (to json_serializer<U>::to_json method with U = uncvref_t<CompatibleType>, to be exact).
Template type CompatibleType includes, but is not limited to, the following types:
array_t and all kinds of compatible containers such as std::vector, std::deque, std::list, std::forward_list, std::array, std::valarray, std::set, std::unordered_set, std::multiset, and std::unordered_multiset with a value_type from which a basic_json value can be constructed.object_t and all kinds of compatible associative containers such as std::map, std::unordered_map, std::multimap, and std::unordered_multimap with a key_type compatible to string_t and a value_type from which a basic_json value can be constructed.string_t, string literals, and all compatible string containers can be used.number_integer_t, number_unsigned_t, number_float_t, and all convertible number types such as int, size_t, int64_t, float or double can be used.boolean_t / bool can be used.binary_t / std::vector<uint8_t> may be used; unfortunately because string literals cannot be distinguished from binary character arrays by the C++ type system, all types compatible with const char* will be directed to the string constructor instead. This is both for backwards compatibility, and due to the fact that a binary type is not a standard JSON type.See the examples below.
This is a constructor for existing basic_json types. It does not hijack copy/move constructors, since the parameter has different template arguments than the current ones.
The constructor tries to convert the internal m_value of the parameter.
Creates a JSON value of type array or object from the passed initializer list init. In case type_deduction is true (default), the type of the JSON value to be created is deducted from the initializer list init according to the following rules:
{} is created.The rules aim to create the best fit between a C++ initializer list and JSON values. The rationale is as follows:
{} which is exactly an empty JSON object.With the rules described above, the following JSON values cannot be expressed by an initializer list:
[]): use array(initializer_list_t) with an empty initializer list in this casearray(initializer_list_t) with the same initializer list in this caseFunction array() and object() force array and object creation from initializer lists, respectively.
Constructs a JSON array value by creating cnt copies of a passed value. In case cnt is 0, an empty array is created.
Constructs the JSON value with the contents of the range [first, last). The semantics depends on the different types a JSON value can have:
null type, invalid_iterator.206 is thrown.first must be begin() and last must be end(). In this case, the value is copied. Otherwise, invalid_iterator.204 is thrown.std::vector or std::map; that is, a JSON array or object is constructed from the values in the range.Creates a copy of a given JSON value.
Move constructor. Constructs a JSON value with the contents of the given value other using move semantics. It "steals" the resources from other and leaves it as JSON null value.
CompatibleTypea type such that:
CompatibleType is not derived from std::istream,CompatibleType is not basic_json (to avoid hijacking copy/move constructors),CompatibleType is not a different basic_json type (i.e. with different template arguments)CompatibleType is not a basic_json nested type (e.g., json_pointer, iterator, etc.)json_serializer<U> (with U = uncvref_t<CompatibleType>) has a to_json(basic_json_t&, CompatibleType&&) methodBasicJsonType:a type such that:
BasicJsonType is a basic_json type.BasicJsonType has different template arguments than basic_json_t.U:uncvref_t<CompatibleType>v (in)val (in)init (in)type_deduction (in)true, the type of the JSON value is deducted from the initializer list init; when set to false, the type provided via manual_type is forced. This mode is used by the functions array(initializer_list_t) and object(initializer_list_t).manual_type (in)type_deduction is set to false, the created JSON value will use the provided type (only value_t::array and value_t::object are valid); when type_deduction is set to true, this parameter has no effectcnt (in)val to createfirst (in)last (in)other (in)to_json() function was provided), strong guarantee holds: if an exception is thrown, there are no changes to any JSON value.to_json() function was provided), strong guarantee holds: if an exception is thrown, there are no changes to any JSON value.type_error.301 if type_deduction is false, manual_type is value_t::object, but init contains an element which is not a pair whose first element is a string. In this case, the constructor could not create an object. If type_deduction would have been true, an array would have been created. See object(initializer_list_t) for an example.invalid_iterator.201 if iterators first and last are not compatible (i.e., do not belong to the same JSON value). In this case, the range [first, last) is undefined.invalid_iterator.204 if iterators first and last belong to a primitive type (number, boolean, or string), but first does not point to the first element anymore. In this case, the range [first, last) is undefined. See example code below.invalid_iterator.206 if iterators first and last belong to a null value. In this case, the range [first, last) is undefined.val, also depending on the implementation of the called to_json() method.val, also depending on the implementation of the called to_json() method.init.cnt.first and last.other.Overload 5:
Empty initializer list
When used without parentheses around an empty initializer list, basic_json() is called instead of this function, yielding the JSON null value.
Overload 7:
Preconditions
first and last must be initialized. **This precondition is enforced with a runtime assertion.[first, last) is valid. Usually, this precondition cannot be checked efficiently. Only certain edge cases are detected; see the description of the exceptions above. A violation of this precondition yields undefined behavior.Runtime assertion
A precondition is enforced with a runtime assertion.
Overload 8:
Postcondition
*this == other
Overload 9:
Postconditions
`*this has the same value as other before the call.other is a JSON null valueThe following code shows the constructor for different value_t values.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create the different JSON values with default values
+ json j_null(json::value_t::null);
+ json j_boolean(json::value_t::boolean);
+ json j_number_integer(json::value_t::number_integer);
+ json j_number_float(json::value_t::number_float);
+ json j_object(json::value_t::object);
+ json j_array(json::value_t::array);
+ json j_string(json::value_t::string);
+
+ // serialize the JSON values
+ std::cout << j_null << '\n';
+ std::cout << j_boolean << '\n';
+ std::cout << j_number_integer << '\n';
+ std::cout << j_number_float << '\n';
+ std::cout << j_object << '\n';
+ std::cout << j_array << '\n';
+ std::cout << j_string << '\n';
+}
+Output:
null
+false
+0
+0.0
+{}
+[]
+""
+null objectThe following code shows the constructor with and without a null pointer parameter.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // implicitly create a JSON null value
+ json j1;
+
+ // explicitly create a JSON null value
+ json j2(nullptr);
+
+ // serialize the JSON null value
+ std::cout << j1 << '\n' << j2 << '\n';
+}
+Output:
null
+null
+The following code shows the constructor with several compatible types.
#include <iostream>
+#include <deque>
+#include <list>
+#include <forward_list>
+#include <set>
+#include <unordered_map>
+#include <unordered_set>
+#include <valarray>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // ============
+ // object types
+ // ============
+
+ // create an object from an object_t value
+ json::object_t object_value = { {"one", 1}, {"two", 2} };
+ json j_object_t(object_value);
+
+ // create an object from std::map
+ std::map<std::string, int> c_map
+ {
+ {"one", 1}, {"two", 2}, {"three", 3}
+ };
+ json j_map(c_map);
+
+ // create an object from std::unordered_map
+ std::unordered_map<const char*, double> c_umap
+ {
+ {"one", 1.2}, {"two", 2.3}, {"three", 3.4}
+ };
+ json j_umap(c_umap);
+
+ // create an object from std::multimap
+ std::multimap<std::string, bool> c_mmap
+ {
+ {"one", true}, {"two", true}, {"three", false}, {"three", true}
+ };
+ json j_mmap(c_mmap); // only one entry for key "three" is used
+
+ // create an object from std::unordered_multimap
+ std::unordered_multimap<std::string, bool> c_ummap
+ {
+ {"one", true}, {"two", true}, {"three", false}, {"three", true}
+ };
+ json j_ummap(c_ummap); // only one entry for key "three" is used
+
+ // serialize the JSON objects
+ std::cout << j_object_t << '\n';
+ std::cout << j_map << '\n';
+ std::cout << j_umap << '\n';
+ std::cout << j_mmap << '\n';
+ std::cout << j_ummap << "\n\n";
+
+
+ // ===========
+ // array types
+ // ===========
+
+ // create an array from an array_t value
+ json::array_t array_value = {"one", "two", 3, 4.5, false};
+ json j_array_t(array_value);
+
+ // create an array from std::vector
+ std::vector<int> c_vector {1, 2, 3, 4};
+ json j_vec(c_vector);
+
+ // create an array from std::valarray
+ std::valarray<short> c_valarray {10, 9, 8, 7};
+ json j_valarray(c_valarray);
+
+ // create an array from std::deque
+ std::deque<double> c_deque {1.2, 2.3, 3.4, 5.6};
+ json j_deque(c_deque);
+
+ // create an array from std::list
+ std::list<bool> c_list {true, true, false, true};
+ json j_list(c_list);
+
+ // create an array from std::forward_list
+ std::forward_list<std::int64_t> c_flist {12345678909876, 23456789098765, 34567890987654, 45678909876543};
+ json j_flist(c_flist);
+
+ // create an array from std::array
+ std::array<unsigned long, 4> c_array {{1, 2, 3, 4}};
+ json j_array(c_array);
+
+ // create an array from std::set
+ std::set<std::string> c_set {"one", "two", "three", "four", "one"};
+ json j_set(c_set); // only one entry for "one" is used
+
+ // create an array from std::unordered_set
+ std::unordered_set<std::string> c_uset {"one", "two", "three", "four", "one"};
+ json j_uset(c_uset); // only one entry for "one" is used
+
+ // create an array from std::multiset
+ std::multiset<std::string> c_mset {"one", "two", "one", "four"};
+ json j_mset(c_mset); // both entries for "one" are used
+
+ // create an array from std::unordered_multiset
+ std::unordered_multiset<std::string> c_umset {"one", "two", "one", "four"};
+ json j_umset(c_umset); // both entries for "one" are used
+
+ // serialize the JSON arrays
+ std::cout << j_array_t << '\n';
+ std::cout << j_vec << '\n';
+ std::cout << j_valarray << '\n';
+ std::cout << j_deque << '\n';
+ std::cout << j_list << '\n';
+ std::cout << j_flist << '\n';
+ std::cout << j_array << '\n';
+ std::cout << j_set << '\n';
+ std::cout << j_uset << '\n';
+ std::cout << j_mset << '\n';
+ std::cout << j_umset << "\n\n";
+
+
+ // ============
+ // string types
+ // ============
+
+ // create string from a string_t value
+ json::string_t string_value = "The quick brown fox jumps over the lazy dog.";
+ json j_string_t(string_value);
+
+ // create a JSON string directly from a string literal
+ json j_string_literal("The quick brown fox jumps over the lazy dog.");
+
+ // create string from std::string
+ std::string s_stdstring = "The quick brown fox jumps over the lazy dog.";
+ json j_stdstring(s_stdstring);
+
+ // serialize the JSON strings
+ std::cout << j_string_t << '\n';
+ std::cout << j_string_literal << '\n';
+ std::cout << j_stdstring << "\n\n";
+
+
+ // ============
+ // number types
+ // ============
+
+ // create a JSON number from number_integer_t
+ json::number_integer_t value_integer_t = -42;
+ json j_integer_t(value_integer_t);
+
+ // create a JSON number from number_unsigned_t
+ json::number_integer_t value_unsigned_t = 17;
+ json j_unsigned_t(value_unsigned_t);
+
+ // create a JSON number from an anonymous enum
+ enum { enum_value = 17 };
+ json j_enum(enum_value);
+
+ // create values of different integer types
+ short n_short = 42;
+ int n_int = -23;
+ long n_long = 1024;
+ int_least32_t n_int_least32_t = -17;
+ uint8_t n_uint8_t = 8;
+
+ // create (integer) JSON numbers
+ json j_short(n_short);
+ json j_int(n_int);
+ json j_long(n_long);
+ json j_int_least32_t(n_int_least32_t);
+ json j_uint8_t(n_uint8_t);
+
+ // create values of different floating-point types
+ json::number_float_t v_ok = 3.141592653589793;
+ json::number_float_t v_nan = NAN;
+ json::number_float_t v_infinity = INFINITY;
+
+ // create values of different floating-point types
+ float n_float = 42.23;
+ float n_float_nan = 1.0f / 0.0f;
+ double n_double = 23.42;
+
+ // create (floating point) JSON numbers
+ json j_ok(v_ok);
+ json j_nan(v_nan);
+ json j_infinity(v_infinity);
+ json j_float(n_float);
+ json j_float_nan(n_float_nan);
+ json j_double(n_double);
+
+ // serialize the JSON numbers
+ std::cout << j_integer_t << '\n';
+ std::cout << j_unsigned_t << '\n';
+ std::cout << j_enum << '\n';
+ std::cout << j_short << '\n';
+ std::cout << j_int << '\n';
+ std::cout << j_long << '\n';
+ std::cout << j_int_least32_t << '\n';
+ std::cout << j_uint8_t << '\n';
+ std::cout << j_ok << '\n';
+ std::cout << j_nan << '\n';
+ std::cout << j_infinity << '\n';
+ std::cout << j_float << '\n';
+ std::cout << j_float_nan << '\n';
+ std::cout << j_double << "\n\n";
+
+
+ // =============
+ // boolean types
+ // =============
+
+ // create boolean values
+ json j_truth = true;
+ json j_falsity = false;
+
+ // serialize the JSON booleans
+ std::cout << j_truth << '\n';
+ std::cout << j_falsity << '\n';
+}
+Output:
{"one":1,"two":2}
+{"one":1,"three":3,"two":2}
+{"one":1.2,"three":3.4,"two":2.3}
+{"one":true,"three":false,"two":true}
+{"one":true,"three":false,"two":true}
+
+["one","two",3,4.5,false]
+[1,2,3,4]
+[10,9,8,7]
+[1.2,2.3,3.4,5.6]
+[true,true,false,true]
+[12345678909876,23456789098765,34567890987654,45678909876543]
+[1,2,3,4]
+["four","one","three","two"]
+["four","three","two","one"]
+["four","one","one","two"]
+["four","two","one","one"]
+
+"The quick brown fox jumps over the lazy dog."
+"The quick brown fox jumps over the lazy dog."
+"The quick brown fox jumps over the lazy dog."
+
+-42
+17
+17
+42
+-23
+1024
+-17
+8
+3.141592653589793
+null
+null
+42.22999954223633
+null
+23.42
+
+true
+false
+Note the output is platform-dependent.
The example below shows how JSON values are created from initializer lists.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create JSON values
+ json j_empty_init_list = json({});
+ json j_object = { {"one", 1}, {"two", 2} };
+ json j_array = {1, 2, 3, 4};
+ json j_nested_object = { {"one", {1}}, {"two", {1, 2}} };
+ json j_nested_array = { {{1}, "one"}, {{1, 2}, "two"} };
+
+ // serialize the JSON value
+ std::cout << j_empty_init_list << '\n';
+ std::cout << j_object << '\n';
+ std::cout << j_array << '\n';
+ std::cout << j_nested_object << '\n';
+ std::cout << j_nested_array << '\n';
+}
+Output:
{}
+{"one":1,"two":2}
+[1,2,3,4]
+{"one":[1],"two":[1,2]}
+[[[1],"one"],[[1,2],"two"]]
+The following code shows examples for creating arrays with several copies of a given value.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create an array by creating copies of a JSON value
+ json value = "Hello";
+ json array_0 = json(0, value);
+ json array_1 = json(1, value);
+ json array_5 = json(5, value);
+
+ // serialize the JSON arrays
+ std::cout << array_0 << '\n';
+ std::cout << array_1 << '\n';
+ std::cout << array_5 << '\n';
+}
+Output:
[]
+["Hello"]
+["Hello","Hello","Hello","Hello","Hello"]
+The example below shows several ways to create JSON values by specifying a subrange with iterators.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create JSON values
+ json j_array = {"alpha", "bravo", "charly", "delta", "easy"};
+ json j_number = 42;
+ json j_object = {{"one", "eins"}, {"two", "zwei"}};
+
+ // create copies using iterators
+ json j_array_range(j_array.begin() + 1, j_array.end() - 2);
+ json j_number_range(j_number.begin(), j_number.end());
+ json j_object_range(j_object.begin(), j_object.find("two"));
+
+ // serialize the values
+ std::cout << j_array_range << '\n';
+ std::cout << j_number_range << '\n';
+ std::cout << j_object_range << '\n';
+
+ // example for an exception
+ try
+ {
+ json j_invalid(j_number.begin() + 1, j_number.end());
+ }
+ catch (json::invalid_iterator& e)
+ {
+ std::cout << e.what() << '\n';
+ }
+}
+Output:
["bravo","charly"]
+42
+{"one":"eins"}
+[json.exception.invalid_iterator.204] iterators out of range
+The following code shows an example for the copy constructor.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create a JSON array
+ json j1 = {"one", "two", 3, 4.5, false};
+
+ // create a copy
+ json j2(j1);
+
+ // serialize the JSON array
+ std::cout << j1 << " = " << j2 << '\n';
+ std::cout << std::boolalpha << (j1 == j2) << '\n';
+}
+Output:
["one","two",3,4.5,false] = ["one","two",3,4.5,false]
+true
+The code below shows the move constructor explicitly called via std::move.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create a JSON value
+ json a = 23;
+
+ // move contents of a to b
+ json b(std::move(a));
+
+ // serialize the JSON arrays
+ std::cout << a << '\n';
+ std::cout << b << '\n';
+}
+Output:
null
+23
+iterator begin() noexcept;
+const_iterator begin() const noexcept;
+Returns an iterator to the first element.
iterator to the first element
No-throw guarantee: this member function never throws exceptions.
Constant.
The following code shows an example for begin().
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create an array value
+ json array = {1, 2, 3, 4, 5};
+
+ // get an iterator to the first element
+ json::iterator it = array.begin();
+
+ // serialize the element that the iterator points to
+ std::cout << *it << '\n';
+}
+Output:
1
+// (1)
+static basic_json binary(const typename binary_t::container_type& init);
+static basic_json binary(typename binary_t::container_type&& init);
+
+// (2)
+static basic_json binary(const typename binary_t::container_type& init,
+ std::uint8_t subtype);
+static basic_json binary(typename binary_t::container_type&& init,
+ std::uint8_t subtype);
+Binary values are part of various binary formats, such as CBOR, MessagePack, and BSON. This constructor is used to create a value for serialization to those formats.
init (in)subtype (in)JSON binary array value
Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
Linear in the size of init; constant for typename binary_t::container_type&& init versions.
Note, this function exists because of the difficulty in correctly specifying the correct template overload in the standard value ctor, as both JSON arrays and JSON binary arrays are backed with some form of a std::vector. Because JSON binary arrays are a non-standard extension it was decided that it would be best to prevent automatic initialization of a binary array type, for backwards compatibility and so it does not happen on accident.
The following code shows how to create a binary value.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create a binary vector
+ std::vector<std::uint8_t> vec = {0xCA, 0xFE, 0xBA, 0xBE};
+
+ // create a binary JSON value with subtype 42
+ json j = json::binary(vec, 42);
+
+ // output type and subtype
+ std::cout << "type: " << j.type_name() << ", subtype: " << j.get_binary().subtype() << std::endl;
+}
+Output:
type: binary, subtype: 42
+using binary_t = byte_container_with_subtype<BinaryType>;
+This type is a type designed to carry binary data that appears in various serialized formats, such as CBOR's Major Type 2, MessagePack's bin, and BSON's generic binary subtype. This type is NOT a part of standard JSON and exists solely for compatibility with these binary types. As such, it is simply defined as an ordered sequence of zero or more byte values.
Additionally, as an implementation detail, the subtype of the binary data is carried around as a std::uint64_t, which is compatible with both of the binary data formats that use binary subtyping, (though the specific numbering is incompatible with each other, and it is up to the user to translate between them). The subtype is added to BinaryType via the helper type byte_container_with_subtype.
CBOR's RFC 7049 describes this type as:
Major type 2: a byte string. The string's length in bytes is represented following the rules for positive integers (major type 0).
MessagePack's documentation on the bin type family describes this type as:
Bin format family stores a byte array in 2, 3, or 5 bytes of extra bytes in addition to the size of the byte array.
BSON's specifications describe several binary types; however, this type is intended to represent the generic binary type which has the description:
Generic binary subtype - This is the most commonly used binary subtype and should be the 'default' for drivers and tools.
None of these impose any limitations on the internal representation other than the basic unit of storage be some type of array whose parts are decomposable into bytes.
The default representation of this binary format is a std::vector<std::uint8_t>, which is a very common way to represent a byte array in modern C++.
BinaryTypeThe default values for BinaryType is std::vector<std::uint8_t>.
Binary Arrays are stored as pointers in a basic_json type. That is, for any access to array values, a pointer of the type binary_t* must be dereferenced.
CBOR
MessagePack
BSON
The following code shows that binary_t is by default, a typedef to nlohmann::byte_container_with_subtype<std::vector<std::uint8_t>>.
#include <iostream>
+#include <iomanip>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ std::cout << std::boolalpha << std::is_same<nlohmann::byte_container_with_subtype<std::vector<std::uint8_t>>, json::binary_t>::value << std::endl;
+}
+Output:
true
+std::uint64_t in version 3.10.0.using boolean_t = BooleanType;
+The type used to store JSON booleans.
RFC 8259 implicitly describes a boolean as a type which differentiates the two literals true and false.
To store objects in C++, a type is defined by the template parameter BooleanType which chooses the type to use.
With the default values for BooleanType (bool), the default value for boolean_t is bool.
Boolean values are stored directly inside a basic_json type.
The following code shows that boolean_t is by default, a typedef to bool.
#include <iostream>
+#include <iomanip>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ std::cout << std::boolalpha << std::is_same<bool, json::boolean_t>::value << std::endl;
+}
+Output:
true
+const_iterator cbegin() const noexcept;
+Returns an iterator to the first element.
iterator to the first element
No-throw guarantee: this member function never throws exceptions.
Constant.
The following code shows an example for cbegin().
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create an array value
+ const json array = {1, 2, 3, 4, 5};
+
+ // get an iterator to the first element
+ json::const_iterator it = array.cbegin();
+
+ // serialize the element that the iterator points to
+ std::cout << *it << '\n';
+}
+Output:
1
+enum class cbor_tag_handler_t
+{
+ error,
+ ignore,
+ store
+};
+This enumeration is used in the from_cbor function to choose how to treat tags:
parse_error exception in case of a tagThe example below shows how the different values of the cbor_tag_handler_t influence the behavior of from_cbor when reading a tagged byte string.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // tagged byte string
+ std::vector<std::uint8_t> vec = {{0xd8, 0x42, 0x44, 0xcA, 0xfe, 0xba, 0xbe}};
+
+ // cbor_tag_handler_t::error throws
+ try
+ {
+ auto b_throw_on_tag = json::from_cbor(vec, true, true, json::cbor_tag_handler_t::error);
+ }
+ catch (json::parse_error& e)
+ {
+ std::cout << e.what() << std::endl;
+ }
+
+ // cbor_tag_handler_t::ignore ignores the tag
+ auto b_ignore_tag = json::from_cbor(vec, true, true, json::cbor_tag_handler_t::ignore);
+ std::cout << b_ignore_tag << std::endl;
+
+ // cbor_tag_handler_t::store stores the tag as binary subtype
+ auto b_store_tag = json::from_cbor(vec, true, true, json::cbor_tag_handler_t::store);
+ std::cout << b_store_tag << std::endl;
+}
+Output:
[json.exception.parse_error.112] parse error at byte 1: syntax error while parsing CBOR value: invalid byte: 0xD8
+{"bytes":[202,254,186,190],"subtype":null}
+{"bytes":[202,254,186,190],"subtype":66}
+store in 3.10.0.const_iterator cend() const noexcept;
+Returns an iterator to one past the last element.
iterator one past the last element
No-throw guarantee: this member function never throws exceptions.
Constant.
The following code shows an example for cend().
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create an array value
+ json array = {1, 2, 3, 4, 5};
+
+ // get an iterator to one past the last element
+ json::const_iterator it = array.cend();
+
+ // decrement the iterator to point to the last element
+ --it;
+
+ // serialize the element that the iterator points to
+ std::cout << *it << '\n';
+}
+Output:
5
+void clear() noexcept;
+Clears the content of a JSON value and resets it to the default value as if basic_json(value_t) would have been called with the current value type from type():
| Value type | initial value |
|---|---|
| null | null |
| boolean | false |
| string | "" |
| number | 0 |
| binary | An empty byte vector |
| object | {} |
| array | [] |
Has the same effect as calling
*this = basic_json(type());
+No-throw guarantee: this function never throws exceptions.
Linear in the size of the JSON value.
All iterators, pointers and references related to this container are invalidated.
The example below shows the effect of clear() to different JSON types.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create JSON values
+ json j_null;
+ json j_boolean = true;
+ json j_number_integer = 17;
+ json j_number_float = 23.42;
+ json j_object = {{"one", 1}, {"two", 2}};
+ json j_array = {1, 2, 4, 8, 16};
+ json j_string = "Hello, world";
+
+ // call clear()
+ j_null.clear();
+ j_boolean.clear();
+ j_number_integer.clear();
+ j_number_float.clear();
+ j_object.clear();
+ j_array.clear();
+ j_string.clear();
+
+ // serialize the cleared values()
+ std::cout << j_null << '\n';
+ std::cout << j_boolean << '\n';
+ std::cout << j_number_integer << '\n';
+ std::cout << j_number_float << '\n';
+ std::cout << j_object << '\n';
+ std::cout << j_array << '\n';
+ std::cout << j_string << '\n';
+}
+Output:
null
+false
+0
+0.0
+{}
+[]
+""
+// (1)
+bool contains(const typename object_t::key_type& key) const;
+
+// (2)
+template<typename KeyType>
+bool contains(KeyType&& key) const;
+
+// (3)
+bool contains(const json_pointer& ptr) const;
+key. If the element is not found or the JSON value is not an object, false is returned.KeyType is comparable with typename object_t::key_type and typename object_comparator_t::is_transparent denotes a type.ptr can be resolved in the current JSON value.KeyTypejson_pointer that is comparable with string_t using object_comparator_t. This can also be a string view (C++17).key (in)ptr (in)true if an element with specified key exists. If no such element with such key is found or the JSON value is not an object, false is returned.true if the JSON pointer can be resolved to a stored value, false otherwise.Strong exception safety: if an exception occurs, the original value stays intact.
parse_error.106 if an array index begins with 0.parse_error.109 if an array index was not a number.Logarithmic in the size of the JSON object.
false when executed on a JSON type that is not an object.Postconditions
If j.contains(x) returns true for a key or JSON pointer x, then it is safe to call j[x].
The example shows how contains() is used.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+using namespace nlohmann::literals;
+
+int main()
+{
+ // create some JSON values
+ json j_object = R"( {"key": "value"} )"_json;
+ json j_array = R"( [1, 2, 3] )"_json;
+
+ // call contains
+ std::cout << std::boolalpha <<
+ "j_object contains 'key': " << j_object.contains("key") << '\n' <<
+ "j_object contains 'another': " << j_object.contains("another") << '\n' <<
+ "j_array contains 'key': " << j_array.contains("key") << std::endl;
+}
+Output:
j_object contains 'key': true
+j_object contains 'another': false
+j_array contains 'key': false
+The example shows how contains() is used.
#include <iostream>
+#include <string_view>
+#include <nlohmann/json.hpp>
+
+using namespace std::string_view_literals;
+using json = nlohmann::json;
+using namespace nlohmann::literals;
+
+int main()
+{
+ // create some JSON values
+ json j_object = R"( {"key": "value"} )"_json;
+ json j_array = R"( [1, 2, 3] )"_json;
+
+ // call contains
+ std::cout << std::boolalpha <<
+ "j_object contains 'key': " << j_object.contains("key"sv) << '\n' <<
+ "j_object contains 'another': " << j_object.contains("another"sv) << '\n' <<
+ "j_array contains 'key': " << j_array.contains("key"sv) << std::endl;
+}
+Output:
j_object contains 'key': true
+j_object contains 'another': false
+j_array contains 'key': false
+The example shows how contains() is used.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+using namespace nlohmann::literals;
+
+int main()
+{
+ // create a JSON value
+ json j =
+ {
+ {"number", 1}, {"string", "foo"}, {"array", {1, 2}}
+ };
+
+ std::cout << std::boolalpha
+ << j.contains("/number"_json_pointer) << '\n'
+ << j.contains("/string"_json_pointer) << '\n'
+ << j.contains("/array"_json_pointer) << '\n'
+ << j.contains("/array/1"_json_pointer) << '\n'
+ << j.contains("/array/-"_json_pointer) << '\n'
+ << j.contains("/array/4"_json_pointer) << '\n'
+ << j.contains("/baz"_json_pointer) << std::endl;
+
+ try
+ {
+ // try to use an array index with leading '0'
+ j.contains("/array/01"_json_pointer);
+ }
+ catch (json::parse_error& e)
+ {
+ std::cout << e.what() << '\n';
+ }
+
+ try
+ {
+ // try to use an array index that is not a number
+ j.contains("/array/one"_json_pointer);
+ }
+ catch (json::parse_error& e)
+ {
+ std::cout << e.what() << '\n';
+ }
+}
+Output:
true
+true
+true
+true
+false
+false
+false
+KeyType to support comparable types in version 3.11.0.// (1)
+size_type count(const typename object_t::key_type& key) const;
+
+// (2)
+template<typename KeyType>
+size_type count(KeyType&& key) const;
+key. If ObjectType is the default std::map type, the return value will always be 0 (key was not found) or 1 (key was found).KeyType is comparable with typename object_t::key_type and typename object_comparator_t::is_transparent denotes a type.KeyTypejson_pointer that is comparable with string_t using object_comparator_t. This can also be a string view (C++17).key (in)Number of elements with key key. If the JSON value is not an object, the return value will be 0.
Strong exception safety: if an exception occurs, the original value stays intact.
Logarithmic in the size of the JSON object.
This method always returns 0 when executed on a JSON type that is not an object.
The example shows how count() is used.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create a JSON object
+ json j_object = {{"one", 1}, {"two", 2}};
+
+ // call count()
+ auto count_two = j_object.count("two");
+ auto count_three = j_object.count("three");
+
+ // print values
+ std::cout << "number of elements with key \"two\": " << count_two << '\n';
+ std::cout << "number of elements with key \"three\": " << count_three << '\n';
+}
+Output:
number of elements with key "two": 1
+number of elements with key "three": 0
+The example shows how count() is used.
#include <iostream>
+#include <string_view>
+#include <nlohmann/json.hpp>
+
+using namespace std::string_view_literals;
+using json = nlohmann::json;
+
+int main()
+{
+ // create a JSON object
+ json j_object = {{"one", 1}, {"two", 2}};
+
+ // call count()
+ auto count_two = j_object.count("two"sv);
+ auto count_three = j_object.count("three"sv);
+
+ // print values
+ std::cout << "number of elements with key \"two\": " << count_two << '\n';
+ std::cout << "number of elements with key \"three\": " << count_three << '\n';
+}
+Output:
number of elements with key "two": 1
+number of elements with key "three": 0
+key type to KeyType&& in version 3.11.0.const_reverse_iterator crbegin() const noexcept;
+Returns an iterator to the reverse-beginning; that is, the last element.
reverse iterator to the first element
No-throw guarantee: this member function never throws exceptions.
Constant.
The following code shows an example for crbegin().
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create an array value
+ json array = {1, 2, 3, 4, 5};
+
+ // get an iterator to the reverse-beginning
+ json::const_reverse_iterator it = array.crbegin();
+
+ // serialize the element that the iterator points to
+ std::cout << *it << '\n';
+}
+Output:
5
+const_reverse_iterator crend() const noexcept;
+Returns an iterator to the reverse-end; that is, one before the first element. This element acts as a placeholder, attempting to access it results in undefined behavior.
reverse iterator to the element following the last element
No-throw guarantee: this member function never throws exceptions.
Constant.
The following code shows an example for eend().
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create an array value
+ json array = {1, 2, 3, 4, 5};
+
+ // get an iterator to the reverse-end
+ json::const_reverse_iterator it = array.crend();
+
+ // increment the iterator to point to the first element
+ --it;
+
+ // serialize the element that the iterator points to
+ std::cout << *it << '\n';
+}
+Output:
1
+using default_object_comparator_t = std::less<StringType>; // until C++14
+
+using default_object_comparator_t = std::less<>; // since C++14
+The default comparator used by object_t.
Since C++14 a transparent comparator is used which prevents unnecessary string construction when looking up a key in an object.
The actual comparator used depends on object_t and can be obtained via object_comparator_t.
The example below demonstrates the default comparator.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ std::cout << std::boolalpha
+ << "one < two : " << json::default_object_comparator_t{}("one", "two") << "\n"
+ << "three < four : " << json::default_object_comparator_t{}("three", "four") << std::endl;
+}
+Output:
one < two : true
+three < four : false
+static basic_json diff(const basic_json& source,
+ const basic_json& target);
+Creates a JSON Patch so that value source can be changed into the value target by calling patch function.
For two JSON values source and target, the following code yields always true:
source.patch(diff(source, target)) == target;
+source (in)target (in)a JSON patch to convert the source to target
Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
Linear in the lengths of source and target.
Currently, only remove, add, and replace operations are generated.
The following code shows how a JSON patch is created as a diff for two JSON values.
#include <iostream>
+#include <iomanip>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+using namespace nlohmann::literals;
+
+int main()
+{
+ // the source document
+ json source = R"(
+ {
+ "baz": "qux",
+ "foo": "bar"
+ }
+ )"_json;
+
+ // the target document
+ json target = R"(
+ {
+ "baz": "boo",
+ "hello": [
+ "world"
+ ]
+ }
+ )"_json;
+
+ // create the patch
+ json patch = json::diff(source, target);
+
+ // roundtrip
+ json patched_source = source.patch(patch);
+
+ // output patch and roundtrip result
+ std::cout << std::setw(4) << patch << "\n\n"
+ << std::setw(4) << patched_source << std::endl;
+}
+Output:
[
+ {
+ "op": "replace",
+ "path": "/baz",
+ "value": "boo"
+ },
+ {
+ "op": "remove",
+ "path": "/foo"
+ },
+ {
+ "op": "add",
+ "path": "/hello",
+ "value": [
+ "world"
+ ]
+ }
+]
+
+{
+ "baz": "boo",
+ "hello": [
+ "world"
+ ]
+}
+string_t dump(const int indent = -1,
+ const char indent_char = ' ',
+ const bool ensure_ascii = false,
+ const error_handler_t error_handler = error_handler_t::strict) const;
+Serialization function for JSON values. The function tries to mimic Python's json.dumps() function, and currently supports its indent and ensure_ascii parameters.
indent (in)indent is nonnegative, then array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. -1 (the default) selects the most compact representation.indent_char (in)indent is greater than 0. The default is (space).ensure_ascii (in)ensure_ascii is true, all non-ASCII characters in the output are escaped with \uXXXX sequences, and the result consists of ASCII characters only.error_handler (in)error_handler_t: strict (throws and exception in case a decoding error occurs; default), replace (replace invalid UTF-8 sequences with U+FFFD), and ignore (ignore invalid UTF-8 sequences during serialization; all bytes are copied to the output unchanged)).string containing the serialization of the JSON value
Strong guarantee: if an exception is thrown, there are no changes to any JSON value.
Throws type_error.316 if a string stored inside the JSON value is not UTF-8 encoded and error_handler is set to strict
Linear.
Binary values are serialized as object containing two keys:
null if the binary has no subtypeThe following example shows the effect of different indent, indent_char, and ensure_ascii parameters to the result of the serialization.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create JSON values
+ json j_object = {{"one", 1}, {"two", 2}};
+ json j_array = {1, 2, 4, 8, 16};
+ json j_string = "Hellö 😀!";
+
+ // call dump()
+ std::cout << "objects:" << '\n'
+ << j_object.dump() << "\n\n"
+ << j_object.dump(-1) << "\n\n"
+ << j_object.dump(0) << "\n\n"
+ << j_object.dump(4) << "\n\n"
+ << j_object.dump(1, '\t') << "\n\n";
+
+ std::cout << "arrays:" << '\n'
+ << j_array.dump() << "\n\n"
+ << j_array.dump(-1) << "\n\n"
+ << j_array.dump(0) << "\n\n"
+ << j_array.dump(4) << "\n\n"
+ << j_array.dump(1, '\t') << "\n\n";
+
+ std::cout << "strings:" << '\n'
+ << j_string.dump() << '\n'
+ << j_string.dump(-1, ' ', true) << '\n';
+
+ // create JSON value with invalid UTF-8 byte sequence
+ json j_invalid = "ä\xA9ü";
+ try
+ {
+ std::cout << j_invalid.dump() << std::endl;
+ }
+ catch (json::type_error& e)
+ {
+ std::cout << e.what() << std::endl;
+ }
+
+ std::cout << "string with replaced invalid characters: "
+ << j_invalid.dump(-1, ' ', false, json::error_handler_t::replace)
+ << "\nstring with ignored invalid characters: "
+ << j_invalid.dump(-1, ' ', false, json::error_handler_t::ignore)
+ << '\n';
+}
+Output:
objects:
+{"one":1,"two":2}
+
+{"one":1,"two":2}
+
+{
+"one": 1,
+"two": 2
+}
+
+{
+ "one": 1,
+ "two": 2
+}
+
+{
+ "one": 1,
+ "two": 2
+}
+
+arrays:
+[1,2,4,8,16]
+
+[1,2,4,8,16]
+
+[
+1,
+2,
+4,
+8,
+16
+]
+
+[
+ 1,
+ 2,
+ 4,
+ 8,
+ 16
+]
+
+[
+ 1,
+ 2,
+ 4,
+ 8,
+ 16
+]
+
+strings:
+"Hellö 😀!"
+"Hell\u00f6 \ud83d\ude00!"
+[json.exception.type_error.316] invalid UTF-8 byte at index 2: 0xA9
+string with replaced invalid characters: "ä�ü"
+string with ignored invalid characters: "äü"
+indent_char, option ensure_ascii and exceptions added in version 3.0.0.template<class... Args>
+std::pair<iterator, bool> emplace(Args&& ... args);
+Inserts a new element into a JSON object constructed in-place with the given args if there is no element with the key in the container. If the function is called on a JSON null value, an empty object is created before appending the value created from args.
Argsbasic_json objectargs (in)basic_jsona pair consisting of an iterator to the inserted element, or the already-existing element if no insertion happened, and a bool denoting whether the insertion took place.
Throws type_error.311 when called on a type other than JSON object or null; example: "cannot use emplace() with number"
Logarithmic in the size of the container, O(log(size())).
The example shows how emplace() can be used to add elements to a JSON object. Note how the null value was silently converted to a JSON object. Further note how no value is added if there was already one value stored with the same key.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create JSON values
+ json object = {{"one", 1}, {"two", 2}};
+ json null;
+
+ // print values
+ std::cout << object << '\n';
+ std::cout << null << '\n';
+
+ // add values
+ auto res1 = object.emplace("three", 3);
+ null.emplace("A", "a");
+ null.emplace("B", "b");
+
+ // the following call will not add an object, because there is already
+ // a value stored at key "B"
+ auto res2 = null.emplace("B", "c");
+
+ // print values
+ std::cout << object << '\n';
+ std::cout << *res1.first << " " << std::boolalpha << res1.second << '\n';
+
+ std::cout << null << '\n';
+ std::cout << *res2.first << " " << std::boolalpha << res2.second << '\n';
+}
+Output:
{"one":1,"two":2}
+null
+{"one":1,"three":3,"two":2}
+3 true
+{"A":"a","B":"b"}
+"b" false
+template<class... Args>
+reference emplace_back(Args&& ... args);
+Creates a JSON value from the passed parameters args to the end of the JSON value. If the function is called on a JSON null value, an empty array is created before appending the value created from args.
Argsbasic_json objectargs (in)basic_jsonreference to the inserted element
Throws type_error.311 when called on a type other than JSON array or null; example: "cannot use emplace_back() with number"
Amortized constant.
The example shows how emplace_back() can be used to add elements to a JSON array. Note how the null value was silently converted to a JSON array.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create JSON values
+ json array = {1, 2, 3, 4, 5};
+ json null;
+
+ // print values
+ std::cout << array << '\n';
+ std::cout << null << '\n';
+
+ // add values
+ array.emplace_back(6);
+ null.emplace_back("first");
+ null.emplace_back(3, "second");
+
+ // print values
+ std::cout << array << '\n';
+ std::cout << null << '\n';
+}
+Output:
[1,2,3,4,5]
+null
+[1,2,3,4,5,6]
+["first",["second","second","second"]]
+bool empty() const noexcept;
+Checks if a JSON value has no elements (i.e. whether its size() is 0).
The return value depends on the different types and is defined as follows:
| Value type | return value |
|---|---|
| null | true |
| boolean | false |
| string | false |
| number | false |
| binary | false |
| object | result of function object_t::empty() |
| array | result of function array_t::empty() |
No-throw guarantee: this function never throws exceptions.
Constant, as long as array_t and object_t satisfy the Container concept; that is, their empty() functions have constant complexity.
bool empty() const noexcept
+{
+ return size() == 0;
+}
+This function does not return whether a string stored as JSON value is empty -- it returns whether the JSON container itself is empty which is false in the case of a string.
The following code uses empty() to check if a JSON object contains any elements.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create JSON values
+ json j_null;
+ json j_boolean = true;
+ json j_number_integer = 17;
+ json j_number_float = 23.42;
+ json j_object = {{"one", 1}, {"two", 2}};
+ json j_object_empty(json::value_t::object);
+ json j_array = {1, 2, 4, 8, 16};
+ json j_array_empty(json::value_t::array);
+ json j_string = "Hello, world";
+
+ // call empty()
+ std::cout << std::boolalpha;
+ std::cout << j_null.empty() << '\n';
+ std::cout << j_boolean.empty() << '\n';
+ std::cout << j_number_integer.empty() << '\n';
+ std::cout << j_number_float.empty() << '\n';
+ std::cout << j_object.empty() << '\n';
+ std::cout << j_object_empty.empty() << '\n';
+ std::cout << j_array.empty() << '\n';
+ std::cout << j_array_empty.empty() << '\n';
+ std::cout << j_string.empty() << '\n';
+}
+Output:
true
+false
+false
+false
+false
+true
+false
+true
+false
+false for binary types in version 3.8.0.iterator end() noexcept;
+const_iterator end() const noexcept;
+Returns an iterator to one past the last element.
iterator one past the last element
No-throw guarantee: this member function never throws exceptions.
Constant.
The following code shows an example for end().
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create an array value
+ json array = {1, 2, 3, 4, 5};
+
+ // get an iterator to one past the last element
+ json::iterator it = array.end();
+
+ // decrement the iterator to point to the last element
+ --it;
+
+ // serialize the element that the iterator points to
+ std::cout << *it << '\n';
+}
+Output:
5
+// (1)
+iterator erase(iterator pos);
+const_iterator erase(const_iterator pos);
+
+// (2)
+iterator erase(iterator first, iterator last);
+const_iterator erase(const_iterator first, const_iterator last);
+
+// (3)
+size_type erase(const typename object_t::key_type& key);
+
+// (4)
+template<typename KeyType>
+size_type erase(KeyType&& key);
+
+// (5)
+void erase(const size_type idx);
+Removes an element from a JSON value specified by iterator pos. The iterator pos must be valid and dereferenceable. Thus, the end() iterator (which is valid, but is not dereferenceable) cannot be used as a value for pos.
If called on a primitive type other than null, the resulting JSON value will be null.
Remove an element range specified by [first; last) from a JSON value. The iterator first does not need to be dereferenceable if first == last: erasing an empty range is a no-op.
If called on a primitive type other than null, the resulting JSON value will be null.
Removes an element from a JSON object by key.
See 3. This overload is only available if KeyType is comparable with typename object_t::key_type and typename object_comparator_t::is_transparent denotes a type.
Removes an element from a JSON array by index.
KeyTypejson_pointer that is comparable with string_t using object_comparator_t. This can also be a string view (C++17).pos (in)first (in)last (in)key (in)idx (in)pos refers to the last element, the end() iterator is returned.last refers to the last element, the end() iterator is returned.ObjectType is the default std::map type, the return value will always be 0 (key was not found) or 1 (key was found).Strong exception safety: if an exception occurs, the original value stays intact.
type_error.307 if called on a null value; example: "cannot use erase() with null"invalid_iterator.202 if called on an iterator which does not belong to the current JSON value; example: "iterator does not fit current value"invalid_iterator.205 if called on a primitive type with invalid iterator (i.e., any iterator which is not begin()); example: "iterator out of range"type_error.307 if called on a null value; example: "cannot use erase() with null"invalid_iterator.203 if called on iterators which does not belong to the current JSON value; example: "iterators do not fit current value"invalid_iterator.204 if called on a primitive type with invalid iterators (i.e., if first != begin() and last != end()); example: "iterators out of range"type_error.307 when called on a type other than JSON object; example: "cannot use erase() with null"type_error.307 when called on a type other than JSON object; example: "cannot use erase() with null"out_of_range.401 when idx >= size(); example: "array index 17 is out of range"pos and the end of the containerlog(size()) + std::distance(first, last)first and last, plus linear in the distance between last and end of the containerlog(size()) + count(key)log(size()) + count(key)idx and the end of the container.erase, including the end() iterator.The example shows the effect of erase() for different JSON types using an iterator.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create JSON values
+ json j_boolean = true;
+ json j_number_integer = 17;
+ json j_number_float = 23.42;
+ json j_object = {{"one", 1}, {"two", 2}};
+ json j_array = {1, 2, 4, 8, 16};
+ json j_string = "Hello, world";
+
+ // call erase()
+ j_boolean.erase(j_boolean.begin());
+ j_number_integer.erase(j_number_integer.begin());
+ j_number_float.erase(j_number_float.begin());
+ j_object.erase(j_object.find("two"));
+ j_array.erase(j_array.begin() + 2);
+ j_string.erase(j_string.begin());
+
+ // print values
+ std::cout << j_boolean << '\n';
+ std::cout << j_number_integer << '\n';
+ std::cout << j_number_float << '\n';
+ std::cout << j_object << '\n';
+ std::cout << j_array << '\n';
+ std::cout << j_string << '\n';
+}
+Output:
null
+null
+null
+{"one":1}
+[1,2,8,16]
+null
+The example shows the effect of erase() for different JSON types using an iterator range.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create JSON values
+ json j_boolean = true;
+ json j_number_integer = 17;
+ json j_number_float = 23.42;
+ json j_object = {{"one", 1}, {"two", 2}};
+ json j_array = {1, 2, 4, 8, 16};
+ json j_string = "Hello, world";
+
+ // call erase()
+ j_boolean.erase(j_boolean.begin(), j_boolean.end());
+ j_number_integer.erase(j_number_integer.begin(), j_number_integer.end());
+ j_number_float.erase(j_number_float.begin(), j_number_float.end());
+ j_object.erase(j_object.find("two"), j_object.end());
+ j_array.erase(j_array.begin() + 1, j_array.begin() + 3);
+ j_string.erase(j_string.begin(), j_string.end());
+
+ // print values
+ std::cout << j_boolean << '\n';
+ std::cout << j_number_integer << '\n';
+ std::cout << j_number_float << '\n';
+ std::cout << j_object << '\n';
+ std::cout << j_array << '\n';
+ std::cout << j_string << '\n';
+}
+Output:
null
+null
+null
+{"one":1}
+[1,8,16]
+null
+The example shows the effect of erase() for different JSON types using an object key.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create a JSON object
+ json j_object = {{"one", 1}, {"two", 2}};
+
+ // call erase()
+ auto count_one = j_object.erase("one");
+ auto count_three = j_object.erase("three");
+
+ // print values
+ std::cout << j_object << '\n';
+ std::cout << count_one << " " << count_three << '\n';
+}
+Output:
{"two":2}
+1 0
+The example shows the effect of erase() for different JSON types using an object key.
#include <iostream>
+#include <string_view>
+#include <nlohmann/json.hpp>
+
+using namespace std::string_view_literals;
+using json = nlohmann::json;
+
+int main()
+{
+ // create a JSON object
+ json j_object = {{"one", 1}, {"two", 2}};
+
+ // call erase()
+ auto count_one = j_object.erase("one"sv);
+ auto count_three = j_object.erase("three"sv);
+
+ // print values
+ std::cout << j_object << '\n';
+ std::cout << count_one << " " << count_three << '\n';
+}
+Output:
{"two":2}
+1 0
+The example shows the effect of erase() using an array index.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create a JSON array
+ json j_array = {0, 1, 2, 3, 4, 5};
+
+ // call erase()
+ j_array.erase(2);
+
+ // print values
+ std::cout << j_array << '\n';
+}
+Output:
[0,1,3,4,5]
+enum class error_handler_t {
+ strict,
+ replace,
+ ignore
+};
+This enumeration is used in the dump function to choose how to treat decoding errors while serializing a basic_json value. Three values are differentiated:
type_error exception in case of invalid UTF-8The example below shows how the different values of the error_handler_t influence the behavior of dump when reading serializing an invalid UTF-8 sequence.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create JSON value with invalid UTF-8 byte sequence
+ json j_invalid = "ä\xA9ü";
+ try
+ {
+ std::cout << j_invalid.dump() << std::endl;
+ }
+ catch (json::type_error& e)
+ {
+ std::cout << e.what() << std::endl;
+ }
+
+ std::cout << "string with replaced invalid characters: "
+ << j_invalid.dump(-1, ' ', false, json::error_handler_t::replace)
+ << "\nstring with ignored invalid characters: "
+ << j_invalid.dump(-1, ' ', false, json::error_handler_t::ignore)
+ << '\n';
+}
+Output:
[json.exception.type_error.316] invalid UTF-8 byte at index 2: 0xA9
+string with replaced invalid characters: "ä�ü"
+string with ignored invalid characters: "äü"
+class exception : public std::exception;
+This class is an extension of std::exception objects with a member id for exception ids. It is used as the base class for all exceptions thrown by the basic_json class. This class can hence be used as "wildcard" to catch exceptions, see example below.
Subclasses:
parse_error for exceptions indicating a parse errorinvalid_iterator for exceptions indicating errors with iteratorstype_error for exceptions indicating executing a member function with a wrong typeout_of_range for exceptions indicating access out of the defined rangeother_error for exceptions indicating other library errorsTo have nothrow-copy-constructible exceptions, we internally use std::runtime_error which can cope with arbitrary-length error messages. Intermediate strings are built with static functions and then passed to the actual constructor.
The following code shows how arbitrary library exceptions can be caught.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ try
+ {
+ // calling at() for a non-existing key
+ json j = {{"foo", "bar"}};
+ json k = j.at("non-existing");
+ }
+ catch (json::exception& e)
+ {
+ // output exception information
+ std::cout << "message: " << e.what() << '\n'
+ << "exception id: " << e.id << std::endl;
+ }
+}
+Output:
message: [json.exception.out_of_range.403] key 'non-existing' not found
+exception id: 403
+// (1)
+iterator find(const typename object_t::key_type& key);
+const_iterator find(const typename object_t::key_type& key) const;
+
+// (2)
+template<typename KeyType>
+iterator find(KeyType&& key);
+template<typename KeyType>
+const_iterator find(KeyType&& key) const;
+key. If the element is not found or the JSON value is not an object, end() is returned.KeyType is comparable with typename object_t::key_type and typename object_comparator_t::is_transparent denotes a type.KeyTypejson_pointer that is comparable with string_t using object_comparator_t. This can also be a string view (C++17).key (in)Iterator to an element with a key equivalent to key. If no such element is found or the JSON value is not an object, a past-the-end iterator (see end()) is returned.
Strong exception safety: if an exception occurs, the original value stays intact.
Logarithmic in the size of the JSON object.
This method always returns end() when executed on a JSON type that is not an object.
The example shows how find() is used.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create a JSON object
+ json j_object = {{"one", 1}, {"two", 2}};
+
+ // call find
+ auto it_two = j_object.find("two");
+ auto it_three = j_object.find("three");
+
+ // print values
+ std::cout << std::boolalpha;
+ std::cout << "\"two\" was found: " << (it_two != j_object.end()) << '\n';
+ std::cout << "value at key \"two\": " << *it_two << '\n';
+ std::cout << "\"three\" was found: " << (it_three != j_object.end()) << '\n';
+}
+Output:
"two" was found: true
+value at key "two": 2
+"three" was found: false
+The example shows how find() is used.
#include <iostream>
+#include <string_view>
+#include <nlohmann/json.hpp>
+
+using namespace std::string_view_literals;
+using json = nlohmann::json;
+
+int main()
+{
+ // create a JSON object
+ json j_object = {{"one", 1}, {"two", 2}};
+
+ // call find
+ auto it_two = j_object.find("two"sv);
+ auto it_three = j_object.find("three"sv);
+
+ // print values
+ std::cout << std::boolalpha;
+ std::cout << "\"two\" was found: " << (it_two != j_object.end()) << '\n';
+ std::cout << "value at key \"two\": " << *it_two << '\n';
+ std::cout << "\"three\" was found: " << (it_three != j_object.end()) << '\n';
+}
+Output:
"two" was found: true
+value at key "two": 2
+"three" was found: false
+basic_json flatten() const;
+The function creates a JSON object whose keys are JSON pointers (see RFC 6901) and whose values are all primitive (see is_primitive() for more information). The original JSON value can be restored using the unflatten() function.
an object that maps JSON pointers to primitive values
Strong exception safety: if an exception occurs, the original value stays intact.
Linear in the size the JSON value.
Empty objects and arrays are flattened to null and will not be reconstructed correctly by the unflatten() function.
The following code shows how a JSON object is flattened to an object whose keys consist of JSON pointers.
#include <iostream>
+#include <iomanip>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create JSON value
+ json j =
+ {
+ {"pi", 3.141},
+ {"happy", true},
+ {"name", "Niels"},
+ {"nothing", nullptr},
+ {
+ "answer", {
+ {"everything", 42}
+ }
+ },
+ {"list", {1, 0, 2}},
+ {
+ "object", {
+ {"currency", "USD"},
+ {"value", 42.99}
+ }
+ }
+ };
+
+ // call flatten()
+ std::cout << std::setw(4) << j.flatten() << '\n';
+}
+Output:
{
+ "/answer/everything": 42,
+ "/happy": true,
+ "/list/0": 1,
+ "/list/1": 0,
+ "/list/2": 2,
+ "/name": "Niels",
+ "/nothing": null,
+ "/object/currency": "USD",
+ "/object/value": 42.99,
+ "/pi": 3.141
+}
+// (1)
+template<typename InputType>
+static basic_json from_bjdata(InputType&& i,
+ const bool strict = true,
+ const bool allow_exceptions = true);
+// (2)
+template<typename IteratorType>
+static basic_json from_bjdata(IteratorType first, IteratorType last,
+ const bool strict = true,
+ const bool allow_exceptions = true);
+Deserializes a given input to a JSON value using the BJData (Binary JData) serialization format.
The exact mapping and its limitations is described on a dedicated page.
InputTypeA compatible input, for instance:
std::istream objectFILE pointerobj for which begin(obj) and end(obj) produces a valid pair of iterators.IteratorTypei (in)first (in)last (in)strict (in)true by default)allow_exceptions (in)true by default)deserialized JSON value; in case of a parse error and allow_exceptions set to false, the return value will be value_t::discarded. The latter can be checked with is_discarded.
Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
strict was set to trueLinear in the size of the input.
The example shows the deserialization of a byte vector in BJData format to a JSON value.
#include <iostream>
+#include <iomanip>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create byte vector
+ std::vector<std::uint8_t> v = {0x7B, 0x69, 0x07, 0x63, 0x6F, 0x6D, 0x70, 0x61,
+ 0x63, 0x74, 0x54, 0x69, 0x06, 0x73, 0x63, 0x68,
+ 0x65, 0x6D, 0x61, 0x69, 0x00, 0x7D
+ };
+
+ // deserialize it with BJData
+ json j = json::from_bjdata(v);
+
+ // print the deserialized JSON value
+ std::cout << std::setw(2) << j << std::endl;
+}
+Output:
{
+ "compact": true,
+ "schema": 0
+}
+// (1)
+template<typename InputType>
+static basic_json from_bson(InputType&& i,
+ const bool strict = true,
+ const bool allow_exceptions = true);
+// (2)
+template<typename IteratorType>
+static basic_json from_bson(IteratorType first, IteratorType last,
+ const bool strict = true,
+ const bool allow_exceptions = true);
+Deserializes a given input to a JSON value using the BSON (Binary JSON) serialization format.
The exact mapping and its limitations is described on a dedicated page.
InputTypeA compatible input, for instance:
std::istream objectFILE pointerobj for which begin(obj) and end(obj) produces a valid pair of iterators.IteratorTypei (in)first (in)last (in)strict (in)true by default)allow_exceptions (in)true by default)deserialized JSON value; in case of a parse error and allow_exceptions set to false, the return value will be value_t::discarded. The latter can be checked with is_discarded.
Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
Throws parse_error.114 if an unsupported BSON record type is encountered.
Linear in the size of the input.
The example shows the deserialization of a byte vector in BSON format to a JSON value.
#include <iostream>
+#include <iomanip>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create byte vector
+ std::vector<std::uint8_t> v = {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
+ };
+
+ // deserialize it with BSON
+ json j = json::from_bson(v);
+
+ // print the deserialized JSON value
+ std::cout << std::setw(2) << j << std::endl;
+}
+Output:
{
+ "compact": true,
+ "schema": 0
+}
+Deprecation
from_bson with a pointer and a length as first two parameters, which has been deprecated in version 3.8.0. This overload will be removed in version 4.0.0. Please replace all calls like from_bson(ptr, len, ...); with from_bson(ptr, ptr+len, ...);.from_bson with a pair of iterators as their first parameter, which has been deprecated in version 3.8.0. This overload will be removed in version 4.0.0. Please replace all calls like from_bson({ptr, ptr+len}, ...); with from_bson(ptr, ptr+len, ...);.You should be warned by your compiler with a -Wdeprecated-declarations warning if you are using a deprecated function.
// (1)
+template<typename InputType>
+static basic_json from_cbor(InputType&& i,
+ const bool strict = true,
+ const bool allow_exceptions = true,
+ const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error);
+
+// (2)
+template<typename IteratorType>
+static basic_json from_cbor(IteratorType first, IteratorType last,
+ const bool strict = true,
+ const bool allow_exceptions = true,
+ const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error);
+Deserializes a given input to a JSON value using the CBOR (Concise Binary Object Representation) serialization format.
The exact mapping and its limitations is described on a dedicated page.
InputTypeA compatible input, for instance:
std::istream objectFILE pointerobj for which begin(obj) and end(obj) produces a valid pair of iterators.IteratorTypei (in)first (in)last (in)strict (in)true by default)allow_exceptions (in)true by default)tag_handler (in)error by default); see cbor_tag_handler_t for more informationdeserialized JSON value; in case of a parse error and allow_exceptions set to false, the return value will be value_t::discarded. The latter can be checked with is_discarded.
Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
strict was set to trueLinear in the size of the input.
The example shows the deserialization of a byte vector in CBOR format to a JSON value.
#include <iostream>
+#include <iomanip>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create byte vector
+ std::vector<std::uint8_t> v = {0xa2, 0x67, 0x63, 0x6f, 0x6d, 0x70, 0x61, 0x63,
+ 0x74, 0xf5, 0x66, 0x73, 0x63, 0x68, 0x65, 0x6d,
+ 0x61, 0x00
+ };
+
+ // deserialize it with CBOR
+ json j = json::from_cbor(v);
+
+ // print the deserialized JSON value
+ std::cout << std::setw(2) << j << std::endl;
+}
+Output:
{
+ "compact": true,
+ "schema": 0
+}
+start_index since version 2.1.1.start_index parameter, and added strict parameter in version 3.0.0.allow_exceptions parameter in version 3.2.0.tag_handler parameter in version 3.9.0.Deprecation
from_cbor with a pointer and a length as first two parameters, which has been deprecated in version 3.8.0. This overload will be removed in version 4.0.0. Please replace all calls like from_cbor(ptr, len, ...); with from_cbor(ptr, ptr+len, ...);.from_cbor with a pair of iterators as their first parameter, which has been deprecated in version 3.8.0. This overload will be removed in version 4.0.0. Please replace all calls like from_cbor({ptr, ptr+len}, ...); with from_cbor(ptr, ptr+len, ...);.You should be warned by your compiler with a -Wdeprecated-declarations warning if you are using a deprecated function.
// (1)
+template<typename InputType>
+static basic_json from_msgpack(InputType&& i,
+ const bool strict = true,
+ const bool allow_exceptions = true);
+// (2)
+template<typename IteratorType>
+static basic_json from_msgpack(IteratorType first, IteratorType last,
+ const bool strict = true,
+ const bool allow_exceptions = true);
+Deserializes a given input to a JSON value using the MessagePack serialization format.
The exact mapping and its limitations is described on a dedicated page.
InputTypeA compatible input, for instance:
std::istream objectFILE pointerobj for which begin(obj) and end(obj) produces a valid pair of iterators.IteratorTypei (in)first (in)last (in)strict (in)true by default)allow_exceptions (in)true by default)deserialized JSON value; in case of a parse error and allow_exceptions set to false, the return value will be value_t::discarded. The latter can be checked with is_discarded.
Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
strict was set to trueLinear in the size of the input.
The example shows the deserialization of a byte vector in MessagePack format to a JSON value.
#include <iostream>
+#include <iomanip>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create byte vector
+ std::vector<std::uint8_t> v = {0x82, 0xa7, 0x63, 0x6f, 0x6d, 0x70, 0x61, 0x63,
+ 0x74, 0xc3, 0xa6, 0x73, 0x63, 0x68, 0x65, 0x6d,
+ 0x61, 0x00
+ };
+
+ // deserialize it with MessagePack
+ json j = json::from_msgpack(v);
+
+ // print the deserialized JSON value
+ std::cout << std::setw(2) << j << std::endl;
+}
+Output:
{
+ "compact": true,
+ "schema": 0
+}
+start_index since version 2.1.1.start_index parameter, and added strict parameter in version 3.0.0.allow_exceptions parameter in version 3.2.0.Deprecation
from_msgpack with a pointer and a length as first two parameters, which has been deprecated in version 3.8.0. This overload will be removed in version 4.0.0. Please replace all calls like from_msgpack(ptr, len, ...); with from_msgpack(ptr, ptr+len, ...);.from_cbor with a pair of iterators as their first parameter, which has been deprecated in version 3.8.0. This overload will be removed in version 4.0.0. Please replace all calls like from_msgpack({ptr, ptr+len}, ...); with from_msgpack(ptr, ptr+len, ...);.You should be warned by your compiler with a -Wdeprecated-declarations warning if you are using a deprecated function.
// (1)
+template<typename InputType>
+static basic_json from_ubjson(InputType&& i,
+ const bool strict = true,
+ const bool allow_exceptions = true);
+// (2)
+template<typename IteratorType>
+static basic_json from_ubjson(IteratorType first, IteratorType last,
+ const bool strict = true,
+ const bool allow_exceptions = true);
+Deserializes a given input to a JSON value using the UBJSON (Universal Binary JSON) serialization format.
The exact mapping and its limitations is described on a dedicated page.
InputTypeA compatible input, for instance:
std::istream objectFILE pointerobj for which begin(obj) and end(obj) produces a valid pair of iterators.IteratorTypei (in)first (in)last (in)strict (in)true by default)allow_exceptions (in)true by default)deserialized JSON value; in case of a parse error and allow_exceptions set to false, the return value will be value_t::discarded. The latter can be checked with is_discarded.
Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
strict was set to trueLinear in the size of the input.
The example shows the deserialization of a byte vector in UBJSON format to a JSON value.
#include <iostream>
+#include <iomanip>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create byte vector
+ std::vector<std::uint8_t> v = {0x7B, 0x69, 0x07, 0x63, 0x6F, 0x6D, 0x70, 0x61,
+ 0x63, 0x74, 0x54, 0x69, 0x06, 0x73, 0x63, 0x68,
+ 0x65, 0x6D, 0x61, 0x69, 0x00, 0x7D
+ };
+
+ // deserialize it with UBJSON
+ json j = json::from_ubjson(v);
+
+ // print the deserialized JSON value
+ std::cout << std::setw(2) << j << std::endl;
+}
+Output:
{
+ "compact": true,
+ "schema": 0
+}
+allow_exceptions parameter in version 3.2.0.Deprecation
from_ubjson with a pointer and a length as first two parameters, which has been deprecated in version 3.8.0. This overload will be removed in version 4.0.0. Please replace all calls like from_ubjson(ptr, len, ...); with from_ubjson(ptr, ptr+len, ...);.from_ubjson with a pair of iterators as their first parameter, which has been deprecated in version 3.8.0. This overload will be removed in version 4.0.0. Please replace all calls like from_ubjson({ptr, ptr+len}, ...); with from_ubjson(ptr, ptr+len, ...);.You should be warned by your compiler with a -Wdeprecated-declarations warning if you are using a deprecated function.
reference front();
+const_reference front() const;
+Returns a reference to the first element in the container. For a JSON container c, the expression c.front() is equivalent to *c.begin().
In case of a structured type (array or object), a reference to the first element is returned. In case of number, string, boolean, or binary values, a reference to the value is returned.
Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
If the JSON value is null, exception invalid_iterator.214 is thrown.
Constant.
Precondition
The array or object must not be empty. Calling front on an empty array or object yields undefined behavior.
The following code shows an example for front().
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create JSON values
+ json j_null;
+ json j_boolean = true;
+ json j_number_integer = 17;
+ json j_number_float = 23.42;
+ json j_object = {{"one", 1}, {"two", 2}};
+ json j_object_empty(json::value_t::object);
+ json j_array = {1, 2, 4, 8, 16};
+ json j_array_empty(json::value_t::array);
+ json j_string = "Hello, world";
+
+ // call front()
+ //std::cout << j_null.front() << '\n'; // would throw
+ std::cout << j_boolean.front() << '\n';
+ std::cout << j_number_integer.front() << '\n';
+ std::cout << j_number_float.front() << '\n';
+ std::cout << j_object.front() << '\n';
+ //std::cout << j_object_empty.front() << '\n'; // undefined behavior
+ std::cout << j_array.front() << '\n';
+ //std::cout << j_array_empty.front() << '\n'; // undefined behavior
+ std::cout << j_string.front() << '\n';
+}
+Output:
true
+17
+23.42
+1
+1
+"Hello, world"
+// (1)
+template<typename ValueType>
+ValueType get() const noexcept(
+ noexcept(JSONSerializer<ValueType>::from_json(
+ std::declval<const basic_json_t&>(), std::declval<ValueType&>())));
+
+// (2)
+template<typename BasicJsonType>
+BasicJsonType get() const;
+
+// (3)
+template<typename PointerType>
+PointerType get_ptr();
+
+template<typename PointerType>
+constexpr const PointerType get_ptr() const noexcept;
+Explicit type conversion between the JSON value and a compatible value which is CopyConstructible and DefaultConstructible. The value is converted by calling the json_serializer<ValueType> from_json() method.
The function is equivalent to executing
ValueType ret;
+JSONSerializer<ValueType>::from_json(*this, ret);
+return ret;
+This overload is chosen if:
ValueType is not basic_json,json_serializer<ValueType> has a from_json() method of the form void from_json(const basic_json&, ValueType&), andjson_serializer<ValueType> does not have a from_json() method of the form ValueType from_json(const basic_json&)If the type is not CopyConstructible and not DefaultConstructible, the value is converted by calling the json_serializer<ValueType> from_json() method.
The function is then equivalent to executing
return JSONSerializer<ValueTypeCV>::from_json(*this);
+This overload is chosen if:
ValueType is not basic_json andjson_serializer<ValueType> has a from_json() method of the form ValueType from_json(const basic_json&)If json_serializer<ValueType> has both overloads of from_json(), the latter one is chosen.
Overload for basic_json specializations. The function is equivalent to executing
return *this;
+Explicit pointer access to the internally stored JSON value. No copies are made.
ValueTypeBasicJsonTypebasic_jsonPointerTypearray_t, object_t, string_t, boolean_t, number_integer_t, or number_unsigned_t, number_float_t, or binary_t. Other types will not compile.ValueType*this, converted into BasicJsonTypenullptr otherwiseDepends on what json_serializer<ValueType> from_json() method throws
Undefined behavior
Writing data to the pointee (overload 3) of the result yields an undefined state.
The example below shows several conversions from JSON values to other types. There a few things to note: (1) Floating-point numbers can be converted to integers, (2) A JSON array can be converted to a standard std::vector<short>, (3) A JSON object can be converted to C++ associative containers such as std::unordered_map<std::string, json>.
#include <iostream>
+#include <unordered_map>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create a JSON value with different types
+ json json_types =
+ {
+ {"boolean", true},
+ {
+ "number", {
+ {"integer", 42},
+ {"floating-point", 17.23}
+ }
+ },
+ {"string", "Hello, world!"},
+ {"array", {1, 2, 3, 4, 5}},
+ {"null", nullptr}
+ };
+
+ // use explicit conversions
+ auto v1 = json_types["boolean"].get<bool>();
+ auto v2 = json_types["number"]["integer"].get<int>();
+ auto v3 = json_types["number"]["integer"].get<short>();
+ auto v4 = json_types["number"]["floating-point"].get<float>();
+ auto v5 = json_types["number"]["floating-point"].get<int>();
+ auto v6 = json_types["string"].get<std::string>();
+ auto v7 = json_types["array"].get<std::vector<short>>();
+ auto v8 = json_types.get<std::unordered_map<std::string, json>>();
+
+ // print the conversion results
+ std::cout << v1 << '\n';
+ std::cout << v2 << ' ' << v3 << '\n';
+ std::cout << v4 << ' ' << v5 << '\n';
+ std::cout << v6 << '\n';
+
+ for (auto i : v7)
+ {
+ std::cout << i << ' ';
+ }
+ std::cout << "\n\n";
+
+ for (auto i : v8)
+ {
+ std::cout << i.first << ": " << i.second << '\n';
+ }
+}
+Output:
1
+42 42
+17.23 17
+Hello, world!
+1 2 3 4 5
+
+string: "Hello, world!"
+number: {"floating-point":17.23,"integer":42}
+null: null
+boolean: true
+array: [1,2,3,4,5]
+The example below shows how pointers to internal values of a JSON value can be requested. Note that no type conversions are made and a #cpp nullptr is returned if the value and the requested pointer type does not match.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create a JSON number
+ json value = 17;
+
+ // explicitly getting pointers
+ auto p1 = value.get<const json::number_integer_t*>();
+ auto p2 = value.get<json::number_integer_t*>();
+ auto p3 = value.get<json::number_integer_t* const>();
+ auto p4 = value.get<const json::number_integer_t* const>();
+ auto p5 = value.get<json::number_float_t*>();
+
+ // print the pointees
+ std::cout << *p1 << ' ' << *p2 << ' ' << *p3 << ' ' << *p4 << '\n';
+ std::cout << std::boolalpha << (p5 == nullptr) << '\n';
+}
+Output:
17 17 17 17
+true
+basic_json in version 3.2.0.static allocator_type get_allocator();
+Returns the allocator associated with the container.
associated allocator
The example shows how get_allocator() is used to created json values.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ auto alloc = json::get_allocator();
+ using traits_t = std::allocator_traits<decltype(alloc)>;
+
+ json* j = traits_t::allocate(alloc, 1);
+ traits_t::construct(alloc, j, "Hello, world!");
+
+ std::cout << *j << std::endl;
+
+ traits_t::destroy(alloc, j);
+ traits_t::deallocate(alloc, j, 1);
+}
+Output:
"Hello, world!"
+binary_t& get_binary();
+
+const binary_t& get_binary() const;
+Returns a reference to the stored binary value.
Reference to binary value.
Strong exception safety: if an exception occurs, the original value stays intact.
Throws type_error.302 if the value is not binary
Constant.
The following code shows how to query a binary value.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create a binary vector
+ std::vector<std::uint8_t> vec = {0xCA, 0xFE, 0xBA, 0xBE};
+
+ // create a binary JSON value with subtype 42
+ json j = json::binary(vec, 42);
+
+ // output type and subtype
+ std::cout << "type: " << j.type_name() << ", subtype: " << j.get_binary().subtype() << std::endl;
+}
+Output:
type: binary, subtype: 42
+template<typename PointerType>
+PointerType get_ptr() noexcept;
+
+template<typename PointerType>
+constexpr const PointerType get_ptr() const noexcept;
+Implicit pointer access to the internally stored JSON value. No copies are made.
PointerTypearray_t, object_t, string_t, boolean_t, number_integer_t, or number_unsigned_t, number_float_t, or binary_t. Other types will not compile.pointer to the internally stored JSON value if the requested pointer type fits to the JSON value; nullptr otherwise
No-throw guarantee: this function never throws exceptions.
Constant.
Undefined behavior
Writing data to the pointee of the result yields an undefined state.
The example below shows how pointers to internal values of a JSON value can be requested. Note that no type conversions are made and a nullptr is returned if the value and the requested pointer type does not match.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create a JSON number
+ json value = 17;
+
+ // explicitly getting pointers
+ auto p1 = value.get_ptr<const json::number_integer_t*>();
+ auto p2 = value.get_ptr<json::number_integer_t*>();
+ auto p3 = value.get_ptr<json::number_integer_t* const>();
+ auto p4 = value.get_ptr<const json::number_integer_t* const>();
+ auto p5 = value.get_ptr<json::number_float_t*>();
+
+ // print the pointees
+ std::cout << *p1 << ' ' << *p2 << ' ' << *p3 << ' ' << *p4 << '\n';
+ std::cout << std::boolalpha << (p5 == nullptr) << '\n';
+}
+Output:
17 17 17 17
+true
+template<typename ReferenceType>
+ReferenceType get_ref();
+
+template<typename ReferenceType>
+const ReferenceType get_ref() const;
+Implicit reference access to the internally stored JSON value. No copies are made.
ReferenceTypearray_t, object_t, string_t, boolean_t, number_integer_t, or number_unsigned_t, number_float_t, or binary_t. Enforced by a static assertion.reference to the internally stored JSON value if the requested reference type fits to the JSON value; throws type_error.303 otherwise
Strong exception safety: if an exception occurs, the original value stays intact.
Throws type_error.303 if the requested reference type does not match the stored JSON value type; example: "incompatible ReferenceType for get_ref, actual type is binary".
Constant.
Undefined behavior
Writing data to the referee of the result yields an undefined state.
The example shows several calls to get_ref().
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create a JSON number
+ json value = 17;
+
+ // explicitly getting references
+ auto r1 = value.get_ref<const json::number_integer_t&>();
+ auto r2 = value.get_ref<json::number_integer_t&>();
+
+ // print the values
+ std::cout << r1 << ' ' << r2 << '\n';
+
+ // incompatible type throws exception
+ try
+ {
+ auto r3 = value.get_ref<json::number_float_t&>();
+ }
+ catch (json::type_error& ex)
+ {
+ std::cout << ex.what() << '\n';
+ }
+}
+Output:
17 17
+[json.exception.type_error.303] incompatible ReferenceType for get_ref, actual type is number
+template<typename ValueType>
+ValueType& get_to(ValueType& v) const noexcept(
+ noexcept(JSONSerializer<ValueType>::from_json(
+ std::declval<const basic_json_t&>(), v)));
+Explicit type conversion between the JSON value and a compatible value. The value is filled into the input parameter by calling the json_serializer<ValueType> from_json() method.
The function is equivalent to executing
ValueType v;
+JSONSerializer<ValueType>::from_json(*this, v);
+This overload is chosen if:
ValueType is not basic_json,json_serializer<ValueType> has a from_json() method of the form void from_json(const basic_json&, ValueType&)ValueTypethe input parameter, allowing chaining calls
Depends on what json_serializer<ValueType> from_json() method throws
The example below shows several conversions from JSON values to other types. There a few things to note: (1) Floating-point numbers can be converted to integers, (2) A JSON array can be converted to a standard std::vector<short>, (3) A JSON object can be converted to C++ associative containers such as #cpp std::unordered_map<std::string, json>.
#include <iostream>
+#include <unordered_map>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create a JSON value with different types
+ json json_types =
+ {
+ {"boolean", true},
+ {
+ "number", {
+ {"integer", 42},
+ {"floating-point", 17.23}
+ }
+ },
+ {"string", "Hello, world!"},
+ {"array", {1, 2, 3, 4, 5}},
+ {"null", nullptr}
+ };
+
+ bool v1;
+ int v2;
+ short v3;
+ float v4;
+ int v5;
+ std::string v6;
+ std::vector<short> v7;
+ std::unordered_map<std::string, json> v8;
+
+
+ // use explicit conversions
+ json_types["boolean"].get_to(v1);
+ json_types["number"]["integer"].get_to(v2);
+ json_types["number"]["integer"].get_to(v3);
+ json_types["number"]["floating-point"].get_to(v4);
+ json_types["number"]["floating-point"].get_to(v5);
+ json_types["string"].get_to(v6);
+ json_types["array"].get_to(v7);
+ json_types.get_to(v8);
+
+ // print the conversion results
+ std::cout << v1 << '\n';
+ std::cout << v2 << ' ' << v3 << '\n';
+ std::cout << v4 << ' ' << v5 << '\n';
+ std::cout << v6 << '\n';
+
+ for (auto i : v7)
+ {
+ std::cout << i << ' ';
+ }
+ std::cout << "\n\n";
+
+ for (auto i : v8)
+ {
+ std::cout << i.first << ": " << i.second << '\n';
+ }
+}
+Output:
1
+42 42
+17.23 17
+Hello, world!
+1 2 3 4 5
+
+string: "Hello, world!"
+number: {"floating-point":17.23,"integer":42}
+null: null
+boolean: true
+array: [1,2,3,4,5]
+Defined in header <nlohmann/json.hpp>
template<
+ template<typename U, typename V, typename... Args> class ObjectType = std::map,
+ template<typename U, typename... Args> class ArrayType = std::vector,
+ class StringType = std::string,
+ class BooleanType = bool,
+ class NumberIntegerType = std::int64_t,
+ class NumberUnsignedType = std::uint64_t,
+ class NumberFloatType = double,
+ template<typename U> class AllocatorType = std::allocator,
+ template<typename T, typename SFINAE = void> class JSONSerializer = adl_serializer,
+ class BinaryType = std::vector<std::uint8_t,
+ class CustomBaseClass = void>
+>
+class basic_json;
+| Template parameter | Description | Derived type |
|---|---|---|
ObjectType | type for JSON objects | object_t |
ArrayType | type for JSON arrays | array_t |
StringType | type for JSON strings and object keys | string_t |
BooleanType | type for JSON booleans | boolean_t |
NumberIntegerType | type for JSON integer numbers | number_integer_t |
NumberUnsignedType | type for JSON unsigned integer numbers | number_unsigned_t |
NumberFloatType | type for JSON floating-point numbers | number_float_t |
AllocatorType | type of the allocator to use | |
JSONSerializer | the serializer to resolve internal calls to to_json() and from_json() | json_serializer |
BinaryType | type for binary arrays | binary_t |
CustomBaseClass | extension point for user code | json_base_class_t |
Todo
The class satisfies the following concept requirements:
==, see operator==.<, see operator<.swap.std::nullptr_t objects which are used to model the null value.basic_json valuesbasic_json class| Type | Definition |
|---|---|
value_type | basic_json |
reference | value_type& |
const_reference | const value_type& |
difference_type | std::ptrdiff_t |
size_type | std::size_t |
allocator_type | AllocatorType<basic_json> |
pointer | std::allocator_traits<allocator_type>::pointer |
const_pointer | std::allocator_traits<allocator_type>::const_pointer |
iterator | LegacyBidirectionalIterator |
const_iterator | constant LegacyBidirectionalIterator |
reverse_iterator | reverse iterator, derived from iterator |
const_reverse_iterator | reverse iterator, derived from const_iterator |
iteration_proxy | helper type for items function |
Functions to inspect the type of a JSON value.
Direct access to the stored value of a JSON value.
Access to the JSON value
to_string function for JSON valuesThe example shows how the library is used.
#include <iostream>
+#include <iomanip>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create a JSON object
+ json j =
+ {
+ {"pi", 3.141},
+ {"happy", true},
+ {"name", "Niels"},
+ {"nothing", nullptr},
+ {
+ "answer", {
+ {"everything", 42}
+ }
+ },
+ {"list", {1, 0, 2}},
+ {
+ "object", {
+ {"currency", "USD"},
+ {"value", 42.99}
+ }
+ }
+ };
+
+ // add new values
+ j["new"]["key"]["value"] = {"another", "list"};
+
+ // count elements
+ auto s = j.size();
+ j["size"] = s;
+
+ // pretty print with indent of 4 spaces
+ std::cout << std::setw(4) << j << '\n';
+}
+Output:
{
+ "answer": {
+ "everything": 42
+ },
+ "happy": true,
+ "list": [
+ 1,
+ 0,
+ 2
+ ],
+ "name": "Niels",
+ "new": {
+ "key": {
+ "value": [
+ "another",
+ "list"
+ ]
+ }
+ },
+ "nothing": null,
+ "object": {
+ "currency": "USD",
+ "value": 42.99
+ },
+ "pi": 3.141,
+ "size": 8
+}
+enum class input_format_t {
+ json,
+ cbor,
+ msgpack,
+ ubjson,
+ bson,
+ bjdata
+};
+This enumeration is used in the sax_parse function to choose the input format to parse:
The example below shows how an input_format_t enum value is passed to sax_parse to set the input format to CBOR.
#include <iostream>
+#include <iomanip>
+#include <sstream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+// a simple event consumer that collects string representations of the passed
+// values; note inheriting from json::json_sax_t is not required, but can
+// help not to forget a required function
+class sax_event_consumer : public json::json_sax_t
+{
+ public:
+ std::vector<std::string> events;
+
+ bool null() override
+ {
+ events.push_back("null()");
+ return true;
+ }
+
+ bool boolean(bool val) override
+ {
+ events.push_back("boolean(val=" + std::string(val ? "true" : "false") + ")");
+ return true;
+ }
+
+ bool number_integer(number_integer_t val) override
+ {
+ events.push_back("number_integer(val=" + std::to_string(val) + ")");
+ return true;
+ }
+
+ bool number_unsigned(number_unsigned_t val) override
+ {
+ events.push_back("number_unsigned(val=" + std::to_string(val) + ")");
+ return true;
+ }
+
+ bool number_float(number_float_t val, const string_t& s) override
+ {
+ events.push_back("number_float(val=" + std::to_string(val) + ", s=" + s + ")");
+ return true;
+ }
+
+ bool string(string_t& val) override
+ {
+ events.push_back("string(val=" + val + ")");
+ return true;
+ }
+
+ bool start_object(std::size_t elements) override
+ {
+ events.push_back("start_object(elements=" + std::to_string(elements) + ")");
+ return true;
+ }
+
+ bool end_object() override
+ {
+ events.push_back("end_object()");
+ return true;
+ }
+
+ bool start_array(std::size_t elements) override
+ {
+ events.push_back("start_array(elements=" + std::to_string(elements) + ")");
+ return true;
+ }
+
+ bool end_array() override
+ {
+ events.push_back("end_array()");
+ return true;
+ }
+
+ bool key(string_t& val) override
+ {
+ events.push_back("key(val=" + val + ")");
+ return true;
+ }
+
+ bool binary(json::binary_t& val) override
+ {
+ events.push_back("binary(val=[...])");
+ return true;
+ }
+
+ bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override
+ {
+ events.push_back("parse_error(position=" + std::to_string(position) + ", last_token=" + last_token + ",\n ex=" + std::string(ex.what()) + ")");
+ return false;
+ }
+};
+
+int main()
+{
+ // CBOR byte string
+ std::vector<std::uint8_t> vec = {{0x44, 0xcA, 0xfe, 0xba, 0xbe}};
+
+ // create a SAX event consumer object
+ sax_event_consumer sec;
+
+ // parse CBOR
+ bool result = json::sax_parse(vec, &sec, json::input_format_t::cbor);
+
+ // output the recorded events
+ for (auto& event : sec.events)
+ {
+ std::cout << event << "\n";
+ }
+
+ // output the result of sax_parse
+ std::cout << "\nresult: " << std::boolalpha << result << std::endl;
+}
+Output:
binary(val=[...])
+
+result: true
+// (1)
+iterator insert(const_iterator pos, const basic_json& val);
+iterator insert(const_iterator pos, basic_json&& val);
+
+// (2)
+iterator insert(const_iterator pos, size_type cnt, const basic_json& val);
+
+// (3)
+iterator insert(const_iterator pos, const_iterator first, const_iterator last);
+
+// (4)
+iterator insert(const_iterator pos, initializer_list_t ilist);
+
+// (5)
+void insert(const_iterator first, const_iterator last);
+val into array before iterator pos.cnt copies of val into array before iterator pos.[first, last) into array before iterator pos.ilist into array before iterator pos.[first, last) into object.pos (in)end() iteratorval (in)cnt (in)val to insertfirst (in)last (in)ilist (in)val.pos if cnt==0pos if first==lastpos if ilist is emptyStrong exception safety: if an exception occurs, the original value stays intact.
type_error.309 if called on JSON values other than arrays; example: "cannot use insert() with string"invalid_iterator.202 if called on an iterator which does not belong to the current JSON value; example: "iterator does not fit current value"type_error.309 if called on JSON values other than arrays; example: "cannot use insert() with string"invalid_iterator.202 if called on an iterator which does not belong to the current JSON value; example: "iterator does not fit current value"type_error.309 if called on JSON values other than arrays; example: "cannot use insert() with string"invalid_iterator.202 if called on an iterator which does not belong to the current JSON value; example: "iterator does not fit current value"invalid_iterator.210 if first and last do not belong to the same JSON value; example: "iterators do not fit"invalid_iterator.211 if first or last are iterators into container for which insert is called; example: "passed iterators may not belong to container"type_error.309 if called on JSON values other than arrays; example: "cannot use insert() with string"invalid_iterator.202 if called on an iterator which does not belong to the current JSON value; example: "iterator does not fit current value"type_error.309 if called on JSON values other than objects; example: "cannot use insert() with string"invalid_iterator.202 if called on an iterator which does not belong to the current JSON value; example: "iterator does not fit current value"invalid_iterator.210 if first and last do not belong to the same JSON value; example: "iterators do not fit"pos and end of the container.cnt plus linear in the distance between pos and end of the container.std::distance(first, last) plus linear in the distance between pos and end of the container.ilist.size() plus linear in the distance between pos and end of the container.O(N*log(size() + N)), where N is the number of elements to insert.The example shows how insert() is used.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create a JSON array
+ json v = {1, 2, 3, 4};
+
+ // insert number 10 before number 3
+ auto new_pos = v.insert(v.begin() + 2, 10);
+
+ // output new array and result of insert call
+ std::cout << *new_pos << '\n';
+ std::cout << v << '\n';
+}
+Output:
10
+[1,2,10,3,4]
+The example shows how insert() is used.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create a JSON array
+ json v = {1, 2, 3, 4};
+
+ // insert number 7 copies of number 7 before number 3
+ auto new_pos = v.insert(v.begin() + 2, 7, 7);
+
+ // output new array and result of insert call
+ std::cout << *new_pos << '\n';
+ std::cout << v << '\n';
+}
+Output:
7
+[1,2,7,7,7,7,7,7,7,3,4]
+The example shows how insert() is used.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create a JSON array
+ json v = {1, 2, 3, 4};
+
+ // create a JSON array to copy values from
+ json v2 = {"one", "two", "three", "four"};
+
+ // insert range from v2 before the end of array v
+ auto new_pos = v.insert(v.end(), v2.begin(), v2.end());
+
+ // output new array and result of insert call
+ std::cout << *new_pos << '\n';
+ std::cout << v << '\n';
+}
+Output:
"one"
+[1,2,3,4,"one","two","three","four"]
+The example shows how insert() is used.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create a JSON array
+ json v = {1, 2, 3, 4};
+
+ // insert range from v2 before the end of array v
+ auto new_pos = v.insert(v.end(), {7, 8, 9});
+
+ // output new array and result of insert call
+ std::cout << *new_pos << '\n';
+ std::cout << v << '\n';
+}
+Output:
7
+[1,2,3,4,7,8,9]
+The example shows how insert() is used.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create two JSON objects
+ json j1 = {{"one", "eins"}, {"two", "zwei"}};
+ json j2 = {{"eleven", "elf"}, {"seventeen", "siebzehn"}};
+
+ // output objects
+ std::cout << j1 << '\n';
+ std::cout << j2 << '\n';
+
+ // insert range from j2 to j1
+ j1.insert(j2.begin(), j2.end());
+
+ // output result of insert call
+ std::cout << j1 << '\n';
+}
+Output:
{"one":"eins","two":"zwei"}
+{"eleven":"elf","seventeen":"siebzehn"}
+{"eleven":"elf","one":"eins","seventeen":"siebzehn","two":"zwei"}
+class invalid_iterator : public exception;
+This exception is thrown if iterators passed to a library function do not match the expected semantics.
Exceptions have ids 2xx (see list of iterator errors).
The following code shows how a invalid_iterator exception can be caught.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ try
+ {
+ // calling iterator::key() on non-object iterator
+ json j = "string";
+ json::iterator it = j.begin();
+ auto k = it.key();
+ }
+ catch (json::invalid_iterator& e)
+ {
+ // output exception information
+ std::cout << "message: " << e.what() << '\n'
+ << "exception id: " << e.id << std::endl;
+ }
+}
+Output:
message: [json.exception.invalid_iterator.207] cannot use key() for non-object iterators
+exception id: 207
+parse_error for exceptions indicating a parse errortype_error for exceptions indicating executing a member function with a wrong typeout_of_range for exceptions indicating access out of the defined rangeother_error for exceptions indicating other library errorsconstexpr bool is_array() const noexcept;
+This function returns true if and only if the JSON value is an array.
true if type is an array, false otherwise.
No-throw guarantee: this member function never throws exceptions.
Constant.
The following code exemplifies is_array() for all JSON types.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create JSON values
+ json j_null;
+ json j_boolean = true;
+ json j_number_integer = 17;
+ json j_number_unsigned_integer = 12345678987654321u;
+ json j_number_float = 23.42;
+ json j_object = {{"one", 1}, {"two", 2}};
+ json j_array = {1, 2, 4, 8, 16};
+ json j_string = "Hello, world";
+ json j_binary = json::binary({1, 2, 3});
+
+ // call is_array()
+ std::cout << std::boolalpha;
+ std::cout << j_null.is_array() << '\n';
+ std::cout << j_boolean.is_array() << '\n';
+ std::cout << j_number_integer.is_array() << '\n';
+ std::cout << j_number_unsigned_integer.is_array() << '\n';
+ std::cout << j_number_float.is_array() << '\n';
+ std::cout << j_object.is_array() << '\n';
+ std::cout << j_array.is_array() << '\n';
+ std::cout << j_string.is_array() << '\n';
+ std::cout << j_binary.is_array() << '\n';
+}
+Output:
false
+false
+false
+false
+false
+false
+true
+false
+false
+constexpr bool is_binary() const noexcept;
+This function returns true if and only if the JSON value is binary array.
true if type is binary, false otherwise.
No-throw guarantee: this member function never throws exceptions.
Constant.
The following code exemplifies is_binary() for all JSON types.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create JSON values
+ json j_null;
+ json j_boolean = true;
+ json j_number_integer = 17;
+ json j_number_unsigned_integer = 12345678987654321u;
+ json j_number_float = 23.42;
+ json j_object = {{"one", 1}, {"two", 2}};
+ json j_array = {1, 2, 4, 8, 16};
+ json j_string = "Hello, world";
+ json j_binary = json::binary({1, 2, 3});
+
+ // call is_binary()
+ std::cout << std::boolalpha;
+ std::cout << j_null.is_binary() << '\n';
+ std::cout << j_boolean.is_binary() << '\n';
+ std::cout << j_number_integer.is_binary() << '\n';
+ std::cout << j_number_unsigned_integer.is_binary() << '\n';
+ std::cout << j_number_float.is_binary() << '\n';
+ std::cout << j_object.is_binary() << '\n';
+ std::cout << j_array.is_binary() << '\n';
+ std::cout << j_string.is_binary() << '\n';
+ std::cout << j_binary.is_binary() << '\n';
+}
+Output:
false
+false
+false
+false
+false
+false
+false
+false
+true
+constexpr bool is_boolean() const noexcept;
+This function returns true if and only if the JSON value is true or false.
true if type is boolean, false otherwise.
No-throw guarantee: this member function never throws exceptions.
Constant.
The following code exemplifies is_boolean() for all JSON types.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create JSON values
+ json j_null;
+ json j_boolean = true;
+ json j_number_integer = 17;
+ json j_number_unsigned_integer = 12345678987654321u;
+ json j_number_float = 23.42;
+ json j_object = {{"one", 1}, {"two", 2}};
+ json j_array = {1, 2, 4, 8, 16};
+ json j_string = "Hello, world";
+ json j_binary = json::binary({1, 2, 3});
+
+ // call is_boolean()
+ std::cout << std::boolalpha;
+ std::cout << j_null.is_boolean() << '\n';
+ std::cout << j_boolean.is_boolean() << '\n';
+ std::cout << j_number_integer.is_boolean() << '\n';
+ std::cout << j_number_unsigned_integer.is_boolean() << '\n';
+ std::cout << j_number_float.is_boolean() << '\n';
+ std::cout << j_object.is_boolean() << '\n';
+ std::cout << j_array.is_boolean() << '\n';
+ std::cout << j_string.is_boolean() << '\n';
+ std::cout << j_binary.is_boolean() << '\n';
+}
+Output:
false
+true
+false
+false
+false
+false
+false
+false
+false
+constexpr bool is_discarded() const noexcept;
+This function returns true for a JSON value if either:
parser_callback_t), orallow_exceptions set to false; see parse for more information.true if type is discarded, false otherwise.
No-throw guarantee: this member function never throws exceptions.
Constant.
Comparisons
Discarded values are never compared equal with operator==. That is, checking whether a JSON value j is discarded will only work via:
j.is_discarded()
+because
j == json::value_t::discarded
+will always be false.
Removal during parsing with callback functions
When a value is discarded by a callback function (see parser_callback_t) during parsing, then it is removed when it is part of a structured value. For instance, if the second value of an array is discarded, instead of [null, discarded, false], the array [null, false] is returned. Only if the top-level value is discarded, the return value of the parse call is discarded.
This function will always be false for JSON values after parsing. That is, discarded values can only occur during parsing, but will be removed when inside a structured value or replaced by null in other cases.
The following code exemplifies is_discarded() for all JSON types.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create JSON values
+ json j_null;
+ json j_boolean = true;
+ json j_number_integer = 17;
+ json j_number_unsigned_integer = 12345678987654321u;
+ json j_number_float = 23.42;
+ json j_object = {{"one", 1}, {"two", 2}};
+ json j_array = {1, 2, 4, 8, 16};
+ json j_string = "Hello, world";
+ json j_binary = json::binary({1, 2, 3});
+
+ // call is_discarded()
+ std::cout << std::boolalpha;
+ std::cout << j_null.is_discarded() << '\n';
+ std::cout << j_boolean.is_discarded() << '\n';
+ std::cout << j_number_integer.is_discarded() << '\n';
+ std::cout << j_number_unsigned_integer.is_discarded() << '\n';
+ std::cout << j_number_float.is_discarded() << '\n';
+ std::cout << j_object.is_discarded() << '\n';
+ std::cout << j_array.is_discarded() << '\n';
+ std::cout << j_string.is_discarded() << '\n';
+ std::cout << j_binary.is_discarded() << '\n';
+}
+Output:
false
+false
+false
+false
+false
+false
+false
+false
+false
+constexpr bool is_null() const noexcept;
+This function returns true if and only if the JSON value is null.
true if type is null, false otherwise.
No-throw guarantee: this member function never throws exceptions.
Constant.
The following code exemplifies is_null() for all JSON types.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create JSON values
+ json j_null;
+ json j_boolean = true;
+ json j_number_integer = 17;
+ json j_number_unsigned_integer = 12345678987654321u;
+ json j_number_float = 23.42;
+ json j_object = {{"one", 1}, {"two", 2}};
+ json j_array = {1, 2, 4, 8, 16};
+ json j_string = "Hello, world";
+ json j_binary = json::binary({1, 2, 3});
+
+ // call is_null()
+ std::cout << std::boolalpha;
+ std::cout << j_null.is_null() << '\n';
+ std::cout << j_boolean.is_null() << '\n';
+ std::cout << j_number_integer.is_null() << '\n';
+ std::cout << j_number_unsigned_integer.is_null() << '\n';
+ std::cout << j_number_float.is_null() << '\n';
+ std::cout << j_object.is_null() << '\n';
+ std::cout << j_array.is_null() << '\n';
+ std::cout << j_string.is_null() << '\n';
+ std::cout << j_binary.is_null() << '\n';
+}
+Output:
true
+false
+false
+false
+false
+false
+false
+false
+false
+constexpr bool is_number() const noexcept;
+This function returns true if and only if the JSON value is a number. This includes both integer (signed and unsigned) and floating-point values.
true if type is number (regardless whether integer, unsigned integer or floating-type), false otherwise.
No-throw guarantee: this member function never throws exceptions.
Constant.
constexpr bool is_number() const noexcept
+{
+ return is_number_integer() || is_number_float();
+}
+The following code exemplifies is_number() for all JSON types.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create JSON values
+ json j_null;
+ json j_boolean = true;
+ json j_number_integer = 17;
+ json j_number_unsigned_integer = 12345678987654321u;
+ json j_number_float = 23.42;
+ json j_object = {{"one", 1}, {"two", 2}};
+ json j_array = {1, 2, 4, 8, 16};
+ json j_string = "Hello, world";
+ json j_binary = json::binary({1, 2, 3});
+
+ // call is_number()
+ std::cout << std::boolalpha;
+ std::cout << j_null.is_number() << '\n';
+ std::cout << j_boolean.is_number() << '\n';
+ std::cout << j_number_integer.is_number() << '\n';
+ std::cout << j_number_unsigned_integer.is_number() << '\n';
+ std::cout << j_number_float.is_number() << '\n';
+ std::cout << j_object.is_number() << '\n';
+ std::cout << j_array.is_number() << '\n';
+ std::cout << j_string.is_number() << '\n';
+ std::cout << j_binary.is_number() << '\n';
+}
+Output:
false
+false
+true
+true
+true
+false
+false
+false
+false
+true for unsigned integers in 2.0.0.constexpr bool is_number_float() const noexcept;
+This function returns true if and only if the JSON value is a floating-point number. This excludes signed and unsigned integer values.
true if type is a floating-point number, false otherwise.
No-throw guarantee: this member function never throws exceptions.
Constant.
The following code exemplifies is_number_float() for all JSON types.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create JSON values
+ json j_null;
+ json j_boolean = true;
+ json j_number_integer = 17;
+ json j_number_unsigned_integer = 12345678987654321u;
+ json j_number_float = 23.42;
+ json j_object = {{"one", 1}, {"two", 2}};
+ json j_array = {1, 2, 4, 8, 16};
+ json j_string = "Hello, world";
+ json j_binary = json::binary({1, 2, 3});
+
+ // call is_number_float()
+ std::cout << std::boolalpha;
+ std::cout << j_null.is_number_float() << '\n';
+ std::cout << j_boolean.is_number_float() << '\n';
+ std::cout << j_number_integer.is_number_float() << '\n';
+ std::cout << j_number_unsigned_integer.is_number_float() << '\n';
+ std::cout << j_number_float.is_number_float() << '\n';
+ std::cout << j_object.is_number_float() << '\n';
+ std::cout << j_array.is_number_float() << '\n';
+ std::cout << j_string.is_number_float() << '\n';
+ std::cout << j_binary.is_number_float() << '\n';
+}
+Output:
false
+false
+false
+false
+true
+false
+false
+false
+false
+constexpr bool is_number_integer() const noexcept;
+This function returns true if and only if the JSON value is a signed or unsigned integer number. This excludes floating-point values.
true if type is an integer or unsigned integer number, false otherwise.
No-throw guarantee: this member function never throws exceptions.
Constant.
The following code exemplifies is_number_integer() for all JSON types.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create JSON values
+ json j_null;
+ json j_boolean = true;
+ json j_number_integer = 17;
+ json j_number_unsigned_integer = 12345678987654321u;
+ json j_number_float = 23.42;
+ json j_object = {{"one", 1}, {"two", 2}};
+ json j_array = {1, 2, 4, 8, 16};
+ json j_string = "Hello, world";
+ json j_binary = json::binary({1, 2, 3});
+
+ // call is_number_integer()
+ std::cout << std::boolalpha;
+ std::cout << j_null.is_number_integer() << '\n';
+ std::cout << j_boolean.is_number_integer() << '\n';
+ std::cout << j_number_integer.is_number_integer() << '\n';
+ std::cout << j_number_unsigned_integer.is_number_integer() << '\n';
+ std::cout << j_number_float.is_number_integer() << '\n';
+ std::cout << j_object.is_number_integer() << '\n';
+ std::cout << j_array.is_number_integer() << '\n';
+ std::cout << j_string.is_number_integer() << '\n';
+ std::cout << j_binary.is_number_integer() << '\n';
+}
+Output:
false
+false
+true
+true
+false
+false
+false
+false
+false
+true for unsigned integers in 2.0.0.constexpr bool is_number_unsigned() const noexcept;
+This function returns true if and only if the JSON value is an unsigned integer number. This excludes floating-point and signed integer values.
true if type is an unsigned integer number, false otherwise.
No-throw guarantee: this member function never throws exceptions.
Constant.
The following code exemplifies is_number_unsigned() for all JSON types.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create JSON values
+ json j_null;
+ json j_boolean = true;
+ json j_number_integer = 17;
+ json j_number_unsigned_integer = 12345678987654321u;
+ json j_number_float = 23.42;
+ json j_object = {{"one", 1}, {"two", 2}};
+ json j_array = {1, 2, 4, 8, 16};
+ json j_string = "Hello, world";
+ json j_binary = json::binary({1, 2, 3});
+
+ // call is_number_unsigned()
+ std::cout << std::boolalpha;
+ std::cout << j_null.is_number_unsigned() << '\n';
+ std::cout << j_boolean.is_number_unsigned() << '\n';
+ std::cout << j_number_integer.is_number_unsigned() << '\n';
+ std::cout << j_number_unsigned_integer.is_number_unsigned() << '\n';
+ std::cout << j_number_float.is_number_unsigned() << '\n';
+ std::cout << j_object.is_number_unsigned() << '\n';
+ std::cout << j_array.is_number_unsigned() << '\n';
+ std::cout << j_string.is_number_unsigned() << '\n';
+ std::cout << j_binary.is_number_unsigned() << '\n';
+}
+Output:
false
+false
+false
+true
+false
+false
+false
+false
+false
+constexpr bool is_object() const noexcept;
+This function returns true if and only if the JSON value is an object.
true if type is an object, false otherwise.
No-throw guarantee: this member function never throws exceptions.
Constant.
The following code exemplifies is_object() for all JSON types.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create JSON values
+ json j_null;
+ json j_boolean = true;
+ json j_number_integer = 17;
+ json j_number_float = 23.42;
+ json j_number_unsigned_integer = 12345678987654321u;
+ json j_object = {{"one", 1}, {"two", 2}};
+ json j_array = {1, 2, 4, 8, 16};
+ json j_string = "Hello, world";
+ json j_binary = json::binary({1, 2, 3});
+
+ // call is_object()
+ std::cout << std::boolalpha;
+ std::cout << j_null.is_object() << '\n';
+ std::cout << j_boolean.is_object() << '\n';
+ std::cout << j_number_integer.is_object() << '\n';
+ std::cout << j_number_unsigned_integer.is_object() << '\n';
+ std::cout << j_number_float.is_object() << '\n';
+ std::cout << j_object.is_object() << '\n';
+ std::cout << j_array.is_object() << '\n';
+ std::cout << j_string.is_object() << '\n';
+ std::cout << j_binary.is_object() << '\n';
+}
+Output:
false
+false
+false
+false
+false
+true
+false
+false
+false
+constexpr bool is_primitive() const noexcept;
+This function returns true if and only if the JSON type is primitive (string, number, boolean, null, binary).
true if type is primitive (string, number, boolean, null, or binary), false otherwise.
No-throw guarantee: this member function never throws exceptions.
Constant.
constexpr bool is_primitive() const noexcept
+{
+ return is_null() || is_string() || is_boolean() || is_number() || is_binary();
+}
+The term primitive stems from RFC 8259:
JSON can represent four primitive types (strings, numbers, booleans, and null) and two structured types (objects and arrays).
This library extends primitive types to binary types, because binary types are roughly comparable to strings. Hence, is_primitive() returns true for binary values.
The following code exemplifies is_primitive() for all JSON types.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create JSON values
+ json j_null;
+ json j_boolean = true;
+ json j_number_integer = 17;
+ json j_number_float = 23.42;
+ json j_number_unsigned_integer = 12345678987654321u;
+ json j_object = {{"one", 1}, {"two", 2}};
+ json j_array = {1, 2, 4, 8, 16};
+ json j_string = "Hello, world";
+ json j_binary = json::binary({1, 2, 3});
+
+ // call is_primitive()
+ std::cout << std::boolalpha;
+ std::cout << j_null.is_primitive() << '\n';
+ std::cout << j_boolean.is_primitive() << '\n';
+ std::cout << j_number_integer.is_primitive() << '\n';
+ std::cout << j_number_unsigned_integer.is_primitive() << '\n';
+ std::cout << j_number_float.is_primitive() << '\n';
+ std::cout << j_object.is_primitive() << '\n';
+ std::cout << j_array.is_primitive() << '\n';
+ std::cout << j_string.is_primitive() << '\n';
+ std::cout << j_binary.is_primitive() << '\n';
+}
+Output:
true
+true
+true
+true
+true
+false
+false
+true
+true
+nulltrue for binary types in version 3.8.0.constexpr bool is_string() const noexcept;
+This function returns true if and only if the JSON value is a string.
true if type is a string, false otherwise.
No-throw guarantee: this member function never throws exceptions.
Constant.
The following code exemplifies is_string() for all JSON types.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create JSON values
+ json j_null;
+ json j_boolean = true;
+ json j_number_integer = 17;
+ json j_number_float = 23.42;
+ json j_number_unsigned_integer = 12345678987654321u;
+ json j_object = {{"one", 1}, {"two", 2}};
+ json j_array = {1, 2, 4, 8, 16};
+ json j_string = "Hello, world";
+ json j_binary = json::binary({1, 2, 3});
+
+ // call is_string()
+ std::cout << std::boolalpha;
+ std::cout << j_null.is_string() << '\n';
+ std::cout << j_boolean.is_string() << '\n';
+ std::cout << j_number_integer.is_string() << '\n';
+ std::cout << j_number_unsigned_integer.is_string() << '\n';
+ std::cout << j_number_float.is_string() << '\n';
+ std::cout << j_object.is_string() << '\n';
+ std::cout << j_array.is_string() << '\n';
+ std::cout << j_string.is_string() << '\n';
+ std::cout << j_binary.is_string() << '\n';
+}
+Output:
false
+false
+false
+false
+false
+false
+false
+true
+false
+constexpr bool is_structured() const noexcept;
+This function returns true if and only if the JSON type is structured (array or object).
true if type is structured (array or object), false otherwise.
No-throw guarantee: this member function never throws exceptions.
Constant.
constexpr bool is_primitive() const noexcept
+{
+ return is_array() || is_object();
+}
+The term structured stems from RFC 8259:
JSON can represent four primitive types (strings, numbers, booleans, and null) and two structured types (objects and arrays).
Note that though strings are containers in C++, they are treated as primitive values in JSON.
The following code exemplifies is_structured() for all JSON types.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create JSON values
+ json j_null;
+ json j_boolean = true;
+ json j_number_integer = 17;
+ json j_number_float = 23.42;
+ json j_number_unsigned_integer = 12345678987654321u;
+ json j_object = {{"one", 1}, {"two", 2}};
+ json j_array = {1, 2, 4, 8, 16};
+ json j_string = "Hello, world";
+ json j_binary = json::binary({1, 2, 3});
+
+ // call is_structured()
+ std::cout << std::boolalpha;
+ std::cout << j_null.is_structured() << '\n';
+ std::cout << j_boolean.is_structured() << '\n';
+ std::cout << j_number_integer.is_structured() << '\n';
+ std::cout << j_number_unsigned_integer.is_structured() << '\n';
+ std::cout << j_number_float.is_structured() << '\n';
+ std::cout << j_object.is_structured() << '\n';
+ std::cout << j_array.is_structured() << '\n';
+ std::cout << j_string.is_structured() << '\n';
+ std::cout << j_binary.is_structured() << '\n';
+}
+Output:
false
+false
+false
+false
+false
+true
+true
+false
+false
+iteration_proxy<iterator> items() noexcept;
+iteration_proxy<const_iterator> items() const noexcept;
+This function allows accessing iterator::key() and iterator::value() during range-based for loops. In these loops, a reference to the JSON values is returned, so there is no access to the underlying iterator.
For loop without items() function:
for (auto it = j_object.begin(); it != j_object.end(); ++it)
+{
+ std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
+}
+Range-based for loop without items() function:
for (auto it : j_object)
+{
+ // "it" is of type json::reference and has no key() member
+ std::cout << "value: " << it << '\n';
+}
+Range-based for loop with items() function:
for (auto& el : j_object.items())
+{
+ std::cout << "key: " << el.key() << ", value:" << el.value() << '\n';
+}
+The items() function also allows using structured bindings (C++17):
for (auto& [key, val] : j_object.items())
+{
+ std::cout << "key: " << key << ", value:" << val << '\n';
+}
+iteration proxy object wrapping the current value with an interface to use in range-based for loops
Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
Constant.
When iterating over an array, key() will return the index of the element as string (see example). For primitive types (e.g., numbers), key() returns an empty string.
Lifetime issues
Using items() on temporary objects is dangerous. Make sure the object's lifetime exceeds the iteration. See https://github.com/nlohmann/json/issues/2040 for more information.
The following code shows an example for items().
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create JSON values
+ json j_object = {{"one", 1}, {"two", 2}};
+ json j_array = {1, 2, 4, 8, 16};
+
+ // example for an object
+ for (auto& x : j_object.items())
+ {
+ std::cout << "key: " << x.key() << ", value: " << x.value() << '\n';
+ }
+
+ // example for an array
+ for (auto& x : j_array.items())
+ {
+ std::cout << "key: " << x.key() << ", value: " << x.value() << '\n';
+ }
+}
+Output:
key: one, value: 1
+key: two, value: 2
+key: 0, value: 1
+key: 1, value: 2
+key: 2, value: 4
+key: 3, value: 8
+key: 4, value: 16
+iterator_wrapper in version 3.0.0.items and deprecated iterator_wrapper in version 3.1.0.Deprecation
This function replaces the static function iterator_wrapper which was introduced in version 1.0.0, but has been deprecated in version 3.1.0. Function iterator_wrapper will be removed in version 4.0.0. Please replace all occurrences of iterator_wrapper(j) with j.items().
You should be warned by your compiler with a -Wdeprecated-declarations warning if you are using a deprecated function.
using json_base_class_t = detail::json_base_class<CustomBaseClass>;
+The base class used to inject custom functionality into each instance of basic_json. Examples of such functionality might be metadata, additional member functions (e.g., visitors), or other application-specific code.
CustomBaseClassbasic_jsonThe default value for CustomBaseClass is void. In this case an empty base class is used and no additional functionality is injected.
The type CustomBaseClass has to be a default-constructible class. basic_json only supports copy/move construction/assignment if CustomBaseClass does so as well.
The following code shows how to inject custom data and methods for each node.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+class visitor_adaptor_with_metadata
+{
+ public:
+ template <class Fnc>
+ void visit(const Fnc& fnc) const;
+
+ int metadata = 42;
+ private:
+ template <class Ptr, class Fnc>
+ void do_visit(const Ptr& ptr, const Fnc& fnc) const;
+};
+
+using json = nlohmann::basic_json <
+ std::map,
+ std::vector,
+ std::string,
+ bool,
+ std::int64_t,
+ std::uint64_t,
+ double,
+ std::allocator,
+ nlohmann::adl_serializer,
+ std::vector<std::uint8_t>,
+ visitor_adaptor_with_metadata
+ >;
+
+template <class Fnc>
+void visitor_adaptor_with_metadata::visit(const Fnc& fnc) const
+{
+ do_visit(json::json_pointer{}, fnc);
+}
+
+template <class Ptr, class Fnc>
+void visitor_adaptor_with_metadata::do_visit(const Ptr& ptr, const Fnc& fnc) const
+{
+ using value_t = nlohmann::detail::value_t;
+ const json& j = *static_cast<const json*>(this);
+ switch (j.type())
+ {
+ case value_t::object:
+ fnc(ptr, j);
+ for (const auto& entry : j.items())
+ {
+ entry.value().do_visit(ptr / entry.key(), fnc);
+ }
+ break;
+ case value_t::array:
+ fnc(ptr, j);
+ for (std::size_t i = 0; i < j.size(); ++i)
+ {
+ j.at(i).do_visit(ptr / std::to_string(i), fnc);
+ }
+ break;
+ case value_t::null:
+ case value_t::string:
+ case value_t::boolean:
+ case value_t::number_integer:
+ case value_t::number_unsigned:
+ case value_t::number_float:
+ case value_t::binary:
+ fnc(ptr, j);
+ break;
+ case value_t::discarded:
+ default:
+ break;
+ }
+}
+
+int main()
+{
+ // create a json object
+ json j;
+ j["null"];
+ j["object"]["uint"] = 1U;
+ j["object"].metadata = 21;
+
+ // visit and output
+ j.visit(
+ [&](const json::json_pointer & p,
+ const json & j)
+ {
+ std::cout << (p.empty() ? std::string{"/"} : p.to_string())
+ << " - metadata = " << j.metadata << " -> " << j.dump() << '\n';
+ });
+}
+Output:
/ - metadata = 42 -> {"null":null,"object":{"uint":1}}
+/null - metadata = 42 -> null
+/object - metadata = 21 -> {"uint":1}
+/object/uint - metadata = 42 -> 1
+template<typename T, typename SFINAE>
+using json_serializer = JSONSerializer<T, SFINAE>;
+Tto_json/from_json functionsSFINAEvoidThe default values for json_serializer is adl_serializer.
The example below shows how a conversion of a non-default-constructible type is implemented via a specialization of the adl_serializer.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+namespace ns
+{
+// a simple struct to model a person (not default constructible)
+struct person
+{
+ person(std::string n, std::string a, int aa)
+ : name(std::move(n)), address(std::move(a)), age(aa)
+ {}
+
+ std::string name;
+ std::string address;
+ int age;
+};
+} // namespace ns
+
+namespace nlohmann
+{
+template <>
+struct adl_serializer<ns::person>
+{
+ static ns::person from_json(const json& j)
+ {
+ return {j.at("name"), j.at("address"), j.at("age")};
+ }
+
+ // Here's the catch! You must provide a to_json method! Otherwise, you
+ // will not be able to convert person to json, since you fully
+ // specialized adl_serializer on that type
+ static void to_json(json& j, ns::person p)
+ {
+ j["name"] = p.name;
+ j["address"] = p.address;
+ j["age"] = p.age;
+ }
+};
+} // namespace nlohmann
+
+int main()
+{
+ json j;
+ j["name"] = "Ned Flanders";
+ j["address"] = "744 Evergreen Terrace";
+ j["age"] = 60;
+
+ auto p = j.get<ns::person>();
+
+ std::cout << p.name << " (" << p.age << ") lives in " << p.address << std::endl;
+}
+Output:
Ned Flanders (60) lives in 744 Evergreen Terrace
+size_type max_size() const noexcept;
+Returns the maximum number of elements a JSON value is able to hold due to system or library implementation limitations, i.e. std::distance(begin(), end()) for the JSON value.
The return value depends on the different types and is defined as follows:
| Value type | return value |
|---|---|
| null | 0 (same as size()) |
| boolean | 1 (same as size()) |
| string | 1 (same as size()) |
| number | 1 (same as size()) |
| binary | 1 (same as size()) |
| object | result of function object_t::max_size() |
| array | result of function array_t::max_size() |
No-throw guarantee: this function never throws exceptions.
Constant, as long as array_t and object_t satisfy the Container concept; that is, their max_size() functions have constant complexity.
This function does not return the maximal length of a string stored as JSON value -- it returns the maximal number of string elements the JSON value can store which is 1.
The following code calls max_size() on the different value types.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create JSON values
+ json j_null;
+ json j_boolean = true;
+ json j_number_integer = 17;
+ json j_number_float = 23.42;
+ json j_object = {{"one", 1}, {"two", 2}};
+ json j_array = {1, 2, 4, 8, 16};
+ json j_string = "Hello, world";
+
+ // call max_size()
+ std::cout << j_null.max_size() << '\n';
+ std::cout << j_boolean.max_size() << '\n';
+ std::cout << j_number_integer.max_size() << '\n';
+ std::cout << j_number_float.max_size() << '\n';
+ std::cout << j_object.max_size() << '\n';
+ std::cout << j_array.max_size() << '\n';
+ std::cout << j_string.max_size() << '\n';
+}
+Output:
0
+1
+1
+1
+115292150460684697
+576460752303423487
+1
+Note the output is platform-dependent.
1 for binary types in version 3.8.0.void merge_patch(const basic_json& apply_patch);
+The merge patch format is primarily intended for use with the HTTP PATCH method as a means of describing a set of modifications to a target resource's content. This function applies a merge patch to the current JSON value.
The function implements the following algorithm from Section 2 of RFC 7396 (JSON Merge Patch):
define MergePatch(Target, Patch):
+ if Patch is an Object:
+ if Target is not an Object:
+ Target = {} // Ignore the contents and set it to an empty Object
+ for each Name/Value pair in Patch:
+ if Value is null:
+ if Name exists in Target:
+ remove the Name/Value pair from Target
+ else:
+ Target[Name] = MergePatch(Target[Name], Value)
+ return Target
+ else:
+ return Patch
+Thereby, Target is the current object; that is, the patch is applied to the current value.
apply_patch (in)Linear in the lengths of apply_patch.
The following code shows how a JSON Merge Patch is applied to a JSON document.
#include <iostream>
+#include <nlohmann/json.hpp>
+#include <iomanip> // for std::setw
+
+using json = nlohmann::json;
+using namespace nlohmann::literals;
+
+int main()
+{
+ // the original document
+ json document = R"({
+ "title": "Goodbye!",
+ "author": {
+ "givenName": "John",
+ "familyName": "Doe"
+ },
+ "tags": [
+ "example",
+ "sample"
+ ],
+ "content": "This will be unchanged"
+ })"_json;
+
+ // the patch
+ json patch = R"({
+ "title": "Hello!",
+ "phoneNumber": "+01-123-456-7890",
+ "author": {
+ "familyName": null
+ },
+ "tags": [
+ "example"
+ ]
+ })"_json;
+
+ // apply the patch
+ document.merge_patch(patch);
+
+ // output original and patched document
+ std::cout << std::setw(4) << document << std::endl;
+}
+Output:
{
+ "author": {
+ "givenName": "John"
+ },
+ "content": "This will be unchanged",
+ "phoneNumber": "+01-123-456-7890",
+ "tags": [
+ "example"
+ ],
+ "title": "Hello!"
+}
+static basic_json meta();
+This function returns a JSON object with information about the library, including the version number and information on the platform and compiler.
JSON object holding version information
| key | description |
|---|---|
compiler | Information on the used compiler. It is an object with the following keys: c++ (the used C++ standard), family (the compiler family; possible values are clang, icc, gcc, ilecpp, msvc, pgcpp, sunpro, and unknown), and version (the compiler version). |
copyright | The copyright line for the library as string. |
name | The name of the library as string. |
platform | The used platform as string. Possible values are win32, linux, apple, unix, and unknown. |
url | The URL of the project as string. |
version | The version of the library. It is an object with the following keys: major, minor, and patch as defined by Semantic Versioning, and string (the version string). |
Strong guarantee: if an exception is thrown, there are no changes to any JSON value.
Constant.
The following code shows an example output of the meta() function.
#include <iostream>
+#include <iomanip>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // call meta()
+ std::cout << std::setw(4) << json::meta() << '\n';
+}
+Output:
{
+ "compiler": {
+ "c++": "201103",
+ "family": "gcc",
+ "version": "12.1.0"
+ },
+ "copyright": "(C) 2013-2022 Niels Lohmann",
+ "name": "JSON for Modern C++",
+ "platform": "apple",
+ "url": "https://github.com/nlohmann/json",
+ "version": {
+ "major": 3,
+ "minor": 11,
+ "patch": 2,
+ "string": "3.11.2"
+ }
+}
+Note the output is platform-dependent.
using number_float_t = NumberFloatType;
+The type used to store JSON numbers (floating-point).
RFC 8259 describes numbers as follows:
The representation of numbers is similar to that used in most programming languages. A number is represented in base 10 using decimal digits. It contains an integer component that may be prefixed with an optional minus sign, which may be followed by a fraction part and/or an exponent part. Leading zeros are not allowed. (...) Numeric values that cannot be represented in the grammar below (such as Infinity and NaN) are not permitted.
This description includes both integer and floating-point numbers. However, C++ allows more precise storage if it is known whether the number is a signed integer, an unsigned integer or a floating-point number. Therefore, three different types, number_integer_t, number_unsigned_t and number_float_t are used.
To store floating-point numbers in C++, a type is defined by the template parameter NumberFloatType which chooses the type to use.
With the default values for NumberFloatType (double), the default value for number_float_t is double.
01.2 will be serialized to 1.2. During deserialization, leading zeros yield an error.null.RFC 8259 states:
This specification allows implementations to set limits on the range and precision of numbers accepted. Since software that implements IEEE 754-2008 binary64 (double precision) numbers is generally available and widely used, good interoperability can be achieved by implementations that expect no more precision or range than these provide, in the sense that implementations will approximate JSON numbers within the expected precision.
This implementation does exactly follow this approach, as it uses double precision floating-point numbers. Note values smaller than -1.79769313486232e+308 and values greater than 1.79769313486232e+308 will be stored as NaN internally and be serialized to null.
Floating-point number values are stored directly inside a basic_json type.
The following code shows that number_float_t is by default, a typedef to double.
#include <iostream>
+#include <iomanip>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ std::cout << std::boolalpha << std::is_same<double, json::number_float_t>::value << std::endl;
+}
+Output:
true
+using number_integer_t = NumberIntegerType;
+The type used to store JSON numbers (integers).
RFC 8259 describes numbers as follows:
The representation of numbers is similar to that used in most programming languages. A number is represented in base 10 using decimal digits. It contains an integer component that may be prefixed with an optional minus sign, which may be followed by a fraction part and/or an exponent part. Leading zeros are not allowed. (...) Numeric values that cannot be represented in the grammar below (such as Infinity and NaN) are not permitted.
This description includes both integer and floating-point numbers. However, C++ allows more precise storage if it is known whether the number is a signed integer, an unsigned integer or a floating-point number. Therefore, three different types, number_integer_t, number_unsigned_t and number_float_t are used.
To store integer numbers in C++, a type is defined by the template parameter NumberIntegerType which chooses the type to use.
With the default values for NumberIntegerType (std::int64_t), the default value for number_integer_t is std::int64_t.
010 will be serialized to 8. During deserialization, leading zeros yield an error.null.RFC 8259 specifies:
An implementation may set limits on the range and precision of numbers.
When the default type is used, the maximal integer number that can be stored is 9223372036854775807 (INT64_MAX) and the minimal integer number that can be stored is -9223372036854775808 (INT64_MIN). Integer numbers that are out of range will yield over/underflow when used in a constructor. During deserialization, too large or small integer numbers will be automatically be stored as number_unsigned_t or number_float_t.
RFC 8259 further states:
Note that when such software is used, numbers that are integers and are in the range [-2^{53}+1, 2^{53}-1] are interoperable in the sense that implementations will agree exactly on their numeric values.
As this range is a subrange of the exactly supported range [INT64_MIN, INT64_MAX], this class's integer type is interoperable.
Integer number values are stored directly inside a basic_json type.
The following code shows that number_integer_t is by default, a typedef to std::int64_t.
#include <iostream>
+#include <iomanip>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ std::cout << std::boolalpha << std::is_same<std::int64_t, json::number_integer_t>::value << std::endl;
+}
+Output:
true
+using number_unsigned_t = NumberUnsignedType;
+The type used to store JSON numbers (unsigned).
RFC 8259 describes numbers as follows:
The representation of numbers is similar to that used in most programming languages. A number is represented in base 10 using decimal digits. It contains an integer component that may be prefixed with an optional minus sign, which may be followed by a fraction part and/or an exponent part. Leading zeros are not allowed. (...) Numeric values that cannot be represented in the grammar below (such as Infinity and NaN) are not permitted.
This description includes both integer and floating-point numbers. However, C++ allows more precise storage if it is known whether the number is a signed integer, an unsigned integer or a floating-point number. Therefore, three different types, number_integer_t, number_unsigned_t and number_float_t are used.
To store unsigned integer numbers in C++, a type is defined by the template parameter NumberUnsignedType which chooses the type to use.
With the default values for NumberUnsignedType (std::uint64_t), the default value for number_unsigned_t is std::uint64_t.
010 will be serialized to 8. During deserialization, leading zeros yield an error.null.RFC 8259 specifies:
An implementation may set limits on the range and precision of numbers.
When the default type is used, the maximal integer number that can be stored is 18446744073709551615 (UINT64_MAX) and the minimal integer number that can be stored is 0. Integer numbers that are out of range will yield over/underflow when used in a constructor. During deserialization, too large or small integer numbers will be automatically be stored as number_integer_t or number_float_t.
RFC 8259 further states:
Note that when such software is used, numbers that are integers and are in the range \f[-2^{53}+1, 2^{53}-1]\f are interoperable in the sense that implementations will agree exactly on their numeric values.
As this range is a subrange (when considered in conjunction with the number_integer_t type) of the exactly supported range [0, UINT64_MAX], this class's integer type is interoperable.
Integer number values are stored directly inside a basic_json type.
The following code shows that number_unsigned_t is by default, a typedef to std::uint64_t.
#include <iostream>
+#include <iomanip>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ std::cout << std::boolalpha << std::is_same<std::uint64_t, json::number_unsigned_t>::value << std::endl;
+}
+Output:
true
+static basic_json object(initializer_list_t init = {});
+Creates a JSON object value from a given initializer list. The initializer lists elements must be pairs, and their first elements must be strings. If the initializer list is empty, the empty object {} is created.
init (in)JSON object value
Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
Throws type_error.301 if init is not a list of pairs whose first elements are strings. In this case, no object can be created. When such a value is passed to basic_json(initializer_list_t, bool, value_t), an array would have been created from the passed initializer list init. See example below.
Linear in the size of init.
This function is only added for symmetry reasons. In contrast to the related function array(initializer_list_t), there are no cases which can only be expressed by this function. That is, any initializer list init can also be passed to the initializer list constructor basic_json(initializer_list_t, bool, value_t).
The following code shows an example for the object function.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create JSON objects
+ json j_no_init_list = json::object();
+ json j_empty_init_list = json::object({});
+ json j_list_of_pairs = json::object({ {"one", 1}, {"two", 2} });
+
+ // serialize the JSON objects
+ std::cout << j_no_init_list << '\n';
+ std::cout << j_empty_init_list << '\n';
+ std::cout << j_list_of_pairs << '\n';
+
+ // example for an exception
+ try
+ {
+ // can only create an object from a list of pairs
+ json j_invalid_object = json::object({{ "one", 1, 2 }});
+ }
+ catch (json::type_error& e)
+ {
+ std::cout << e.what() << '\n';
+ }
+}
+Output:
{}
+{}
+{"one":1,"two":2}
+[json.exception.type_error.301] cannot create object from initializer list
+basic_json(initializer_list_t) - create a JSON value from an initializer listarray - create a JSON array value from an initializer listusing object_comparator_t = typename object_t::key_compare;
+// or
+using object_comparator_t = default_object_comparator_t;
+The comparator used by object_t. Defined as typename object_t::key_compare if available, and default_object_comparator_t otherwise.
The example below demonstrates the used object comparator.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ std::cout << std::boolalpha
+ << "json::object_comparator_t(\"one\", \"two\") = " << json::object_comparator_t{}("one", "two") << "\n"
+ << "json::object_comparator_t(\"three\", \"four\") = " << json::object_comparator_t{}("three", "four") << std::endl;
+}
+Output:
json::object_comparator_t("one", "two") = true
+json::object_comparator_t("three", "four") = false
+typename object_t::key_compare or default_object_comparator_t in version 3.11.0.using object_t = ObjectType<StringType,
+ basic_json,
+ default_object_comparator_t,
+ AllocatorType<std::pair<const StringType, basic_json>>>;
+The type used to store JSON objects.
RFC 8259 describes JSON objects as follows:
An object is an unordered collection of zero or more name/value pairs, where a name is a string and a value is a string, number, boolean, null, object, or array.
To store objects in C++, a type is defined by the template parameters described below.
ObjectTypestd::map or std::unordered_map)StringTypestd::string). The comparison function std::less<StringType> is used to order elements inside the container.AllocatorTypestd::allocator)With the default values for ObjectType (std::map), StringType (std::string), and AllocatorType (std::allocator), the default value for object_t is:
// until C++14
+std::map<
+ std::string, // key_type
+ basic_json, // value_type
+ std::less<std::string>, // key_compare
+ std::allocator<std::pair<const std::string, basic_json>> // allocator_type
+>
+
+// since C++14
+std::map<
+ std::string, // key_type
+ basic_json, // value_type
+ std::less<>, // key_compare
+ std::allocator<std::pair<const std::string, basic_json>> // allocator_type
+>
+See default_object_comparator_t for more information.
The choice of object_t influences the behavior of the JSON class. With the default type, objects have the following behavior:
{"key": 2, "key": 1} could be equal to either {"key": 1} or {"key": 2}.dump) in this order. For instance, {"b": 1, "a": 2} and {"a": 2, "b": 1} will be stored and serialized as {"a": 2, "b": 1}.{"b": 1, "a": 2} and {"a": 2, "b": 1} will be treated as equal.RFC 8259 specifies:
An implementation may set limits on the maximum depth of nesting.
In this class, the object's limit of nesting is not explicitly constrained. However, a maximum depth of nesting may be introduced by the compiler or runtime environment. A theoretical limit can be queried by calling the max_size function of a JSON object.
Objects are stored as pointers in a basic_json type. That is, for any access to object values, a pointer of type object_t* must be dereferenced.
The order name/value pairs are added to the object is not preserved by the library. Therefore, iterating an object may return name/value pairs in a different order than they were originally stored. In fact, keys will be traversed in alphabetical order as std::map with std::less is used by default. Please note this behavior conforms to RFC 8259, because any order implements the specified "unordered" nature of JSON objects.
The following code shows that object_t is by default, a typedef to std::map<json::string_t, json>.
#include <iostream>
+#include <iomanip>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ std::cout << std::boolalpha << std::is_same<std::map<json::string_t, json>, json::object_t>::value << std::endl;
+}
+Output:
true
+// (1)
+reference operator+=(basic_json&& val);
+reference operator+=(const basic_json& val);
+
+// (2)
+reference operator+=(const typename object_t::value_type& val);
+
+// (3)
+reference operator+=(initializer_list_t init);
+Appends the given element val to the end of the JSON array. If the function is called on a JSON null value, an empty array is created before appending val.
Inserts the given element val to the JSON object. If the function is called on a JSON null value, an empty object is created before inserting val.
This function allows using operator+= with an initializer list. In case
init contains only two elements, andinit is a string,init is converted into an object element and added using operator+=(const typename object_t::value_type&). Otherwise, init is converted to a JSON value and added using operator+=(basic_json&&).
val (in)init (in)*this
All functions can throw the following exception: - Throws type_error.308 when called on a type other than JSON array or null; example: "cannot use operator+=() with number"
size())).init.(3) This function is required to resolve an ambiguous overload error, because pairs like {"key", "value"} can be both interpreted as object_t::value_type or std::initializer_list<basic_json>, see #235 for more information.
The example shows how push_back() and += can be used to add elements to a JSON array. Note how the null value was silently converted to a JSON array.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create JSON values
+ json array = {1, 2, 3, 4, 5};
+ json null;
+
+ // print values
+ std::cout << array << '\n';
+ std::cout << null << '\n';
+
+ // add values
+ array.push_back(6);
+ array += 7;
+ null += "first";
+ null += "second";
+
+ // print values
+ std::cout << array << '\n';
+ std::cout << null << '\n';
+}
+Output:
[1,2,3,4,5]
+null
+[1,2,3,4,5,6,7]
+["first","second"]
+The example shows how push_back() and += can be used to add elements to a JSON object. Note how the null value was silently converted to a JSON object.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create JSON values
+ json object = {{"one", 1}, {"two", 2}};
+ json null;
+
+ // print values
+ std::cout << object << '\n';
+ std::cout << null << '\n';
+
+ // add values
+ object.push_back(json::object_t::value_type("three", 3));
+ object += json::object_t::value_type("four", 4);
+ null += json::object_t::value_type("A", "a");
+ null += json::object_t::value_type("B", "b");
+
+ // print values
+ std::cout << object << '\n';
+ std::cout << null << '\n';
+}
+Output:
{"one":1,"two":2}
+null
+{"four":4,"one":1,"three":3,"two":2}
+{"A":"a","B":"b"}
+The example shows how initializer lists are treated as objects when possible.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create JSON values
+ json object = {{"one", 1}, {"two", 2}};
+ json null;
+
+ // print values
+ std::cout << object << '\n';
+ std::cout << null << '\n';
+
+ // add values:
+ object.push_back({"three", 3}); // object is extended
+ object += {"four", 4}; // object is extended
+ null.push_back({"five", 5}); // null is converted to array
+
+ // print values
+ std::cout << object << '\n';
+ std::cout << null << '\n';
+
+ // would throw:
+ //object.push_back({1, 2, 3});
+}
+Output:
{"one":1,"two":2}
+null
+{"four":4,"one":1,"three":3,"two":2}
+[["five",5]]
+basic_json& operator=(basic_json other) noexcept (
+ std::is_nothrow_move_constructible<value_t>::value &&
+ std::is_nothrow_move_assignable<value_t>::value &&
+ std::is_nothrow_move_constructible<json_value>::value &&
+ std::is_nothrow_move_assignable<json_value>::value
+);
+Copy assignment operator. Copies a JSON value via the "copy and swap" strategy: It is expressed in terms of the copy constructor, destructor, and the swap() member function.
other (in)Linear.
The code below shows and example for the copy assignment. It creates a copy of value a which is then swapped with b. Finally, the copy of a (which is the null value after the swap) is destroyed.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create JSON values
+ json a = 23;
+ json b = 42;
+
+ // copy-assign a to b
+ b = a;
+
+ // serialize the JSON arrays
+ std::cout << a << '\n';
+ std::cout << b << '\n';
+}
+Output:
23
+23
+// (1)
+reference operator[](size_type idx);
+const_reference operator[](size_type idx) const;
+
+// (2)
+reference operator[](typename object_t::key_type key);
+const_reference operator[](const typename object_t::key_type& key) const;
+
+// (3)
+template<typename KeyType>
+reference operator[](KeyType&& key);
+template<typename KeyType>
+const_reference operator[](KeyType&& key) const;
+
+// (4)
+reference operator[](const json_pointer& ptr);
+const_reference operator[](const json_pointer& ptr) const;
+idx.key. The non-const qualified overload takes the key by value.KeyType is comparable with typename object_t::key_type and typename object_comparator_t::is_transparent denotes a type.ptr.KeyTypejson_pointer that is comparable with string_t using object_comparator_t. This can also be a string view (C++17).idx (in)key (in)ptr (in)idxkeykeyptrStrong exception safety: if an exception occurs, the original value stays intact.
type_error.305 if the JSON value is not an array or null; in that case, using the [] operator with an index makes no sense.type_error.305 if the JSON value is not an object or null; in that case, using the [] operator with a key makes no sense.parse_error.106 if an array index in the passed JSON pointer ptr begins with '0'.parse_error.109 if an array index in the passed JSON pointer ptr is not a number.out_of_range.402 if the array index '-' is used in the passed JSON pointer ptr for the const version.out_of_range.404 if the JSON pointer ptr can not be resolved.idx is in the range of the array. Otherwise, linear in idx - size().Undefined behavior and runtime assertions
idx does not exist, the behavior is undefined.key does not exist, the behavior is undefined and is guarded by a runtime assertion!The non-const version may add values: If idx is beyond the range of the array (i.e., idx >= size()), then the array is silently filled up with null values to make idx a valid reference to the last stored element. In case the value was null before, it is converted to an array.
If key is not found in the object, then it is silently added to the object and filled with a null value to make key a valid reference. In case the value was null before, it is converted to an object.
See 2.
null values are created in arrays and objects if necessary.
In particular:
null value before a reference to it is returned.null value before a reference to it is returned. All indices between the current maximum and the given index are also filled with null.- is treated as a synonym for the index past the end.The example below shows how array elements can be read and written using [] operator. Note the addition of null values.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create a JSON array
+ json array = {1, 2, 3, 4, 5};
+
+ // output element at index 3 (fourth element)
+ std::cout << array[3] << '\n';
+
+ // change last element to 6
+ array[array.size() - 1] = 6;
+
+ // output changed array
+ std::cout << array << '\n';
+
+ // write beyond array limit
+ array[10] = 11;
+
+ // output changed array
+ std::cout << array << '\n';
+}
+Output:
4
+[1,2,3,4,6]
+[1,2,3,4,6,null,null,null,null,null,11]
+The example below shows how array elements can be read using the [] operator.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create JSON array
+ const json array = {"first", "2nd", "third", "fourth"};
+
+ // output element at index 2 (third element)
+ std::cout << array.at(2) << '\n';
+}
+Output:
"third"
+The example below shows how object elements can be read and written using the [] operator.
#include <iostream>
+#include <iomanip>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create a JSON object
+ json object =
+ {
+ {"one", 1}, {"two", 2}, {"three", 2.9}
+ };
+
+ // output element with key "two"
+ std::cout << object["two"] << "\n\n";
+
+ // change element with key "three"
+ object["three"] = 3;
+
+ // output changed array
+ std::cout << std::setw(4) << object << "\n\n";
+
+ // mention nonexisting key
+ object["four"];
+
+ // write to nonexisting key
+ object["five"]["really"]["nested"] = true;
+
+ // output changed object
+ std::cout << std::setw(4) << object << '\n';
+}
+Output:
2
+
+{
+ "one": 1,
+ "three": 3,
+ "two": 2
+}
+
+{
+ "five": {
+ "really": {
+ "nested": true
+ }
+ },
+ "four": null,
+ "one": 1,
+ "three": 3,
+ "two": 2
+}
+The example below shows how object elements can be read using the [] operator.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create a JSON object
+ const json object =
+ {
+ {"one", 1}, {"two", 2}, {"three", 2.9}
+ };
+
+ // output element with key "two"
+ std::cout << object["two"] << '\n';
+}
+Output:
2
+The example below shows how object elements can be read using the [] operator.
#include <iostream>
+#include <iomanip>
+#include <string_view>
+#include <nlohmann/json.hpp>
+
+using namespace std::string_view_literals;
+using json = nlohmann::json;
+
+int main()
+{
+ // create a JSON object
+ json object =
+ {
+ {"one", 1}, {"two", 2}, {"three", 2.9}
+ };
+
+ // output element with key "two"
+ std::cout << object["two"sv] << "\n\n";
+
+ // change element with key "three"
+ object["three"sv] = 3;
+
+ // output changed array
+ std::cout << std::setw(4) << object << "\n\n";
+
+ // mention nonexisting key
+ object["four"sv];
+
+ // write to nonexisting key
+ object["five"sv]["really"sv]["nested"sv] = true;
+
+ // output changed object
+ std::cout << std::setw(4) << object << '\n';
+}
+Output:
2
+
+{
+ "one": 1,
+ "three": 3,
+ "two": 2
+}
+
+{
+ "five": {
+ "really": {
+ "nested": true
+ }
+ },
+ "four": null,
+ "one": 1,
+ "three": 3,
+ "two": 2
+}
+The example below shows how object elements can be read using the [] operator.
#include <iostream>
+#include <string_view>
+#include <nlohmann/json.hpp>
+
+using namespace std::string_view_literals;
+using json = nlohmann::json;
+
+int main()
+{
+ // create a JSON object
+ const json object =
+ {
+ {"one", 1}, {"two", 2}, {"three", 2.9}
+ };
+
+ // output element with key "two"
+ std::cout << object["two"sv] << '\n';
+}
+Output:
2
+The example below shows how values can be read and written using JSON Pointers.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+using namespace nlohmann::literals;
+
+int main()
+{
+ // create a JSON value
+ json j =
+ {
+ {"number", 1}, {"string", "foo"}, {"array", {1, 2}}
+ };
+
+ // read-only access
+
+ // output element with JSON pointer "/number"
+ std::cout << j["/number"_json_pointer] << '\n';
+ // output element with JSON pointer "/string"
+ std::cout << j["/string"_json_pointer] << '\n';
+ // output element with JSON pointer "/array"
+ std::cout << j["/array"_json_pointer] << '\n';
+ // output element with JSON pointer "/array/1"
+ std::cout << j["/array/1"_json_pointer] << '\n';
+
+ // writing access
+
+ // change the string
+ j["/string"_json_pointer] = "bar";
+ // output the changed string
+ std::cout << j["string"] << '\n';
+
+ // "change" a nonexisting object entry
+ j["/boolean"_json_pointer] = true;
+ // output the changed object
+ std::cout << j << '\n';
+
+ // change an array element
+ j["/array/1"_json_pointer] = 21;
+ // "change" an array element with nonexisting index
+ j["/array/4"_json_pointer] = 44;
+ // output the changed array
+ std::cout << j["array"] << '\n';
+
+ // "change" the array element past the end
+ j["/array/-"_json_pointer] = 55;
+ // output the changed array
+ std::cout << j["array"] << '\n';
+}
+Output:
1
+"foo"
+[1,2]
+2
+"bar"
+{"array":[1,2],"boolean":true,"number":1,"string":"bar"}
+[1,21,null,null,44]
+[1,21,null,null,44,55]
+The example below shows how values can be read using JSON Pointers.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+using namespace nlohmann::literals;
+
+int main()
+{
+ // create a JSON value
+ const json j =
+ {
+ {"number", 1}, {"string", "foo"}, {"array", {1, 2}}
+ };
+
+ // read-only access
+
+ // output element with JSON pointer "/number"
+ std::cout << j["/number"_json_pointer] << '\n';
+ // output element with JSON pointer "/string"
+ std::cout << j["/string"_json_pointer] << '\n';
+ // output element with JSON pointer "/array"
+ std::cout << j["/array"_json_pointer] << '\n';
+ // output element with JSON pointer "/array/1"
+ std::cout << j["/array/1"_json_pointer] << '\n';
+}
+Output:
1
+"foo"
+[1,2]
+2
+at for access by reference with range checkingvalue for access with default valueT* key in version 1.1.0. Removed overloads for T* key (replaced by 3) in version 3.11.0.template<typename ValueType>
+JSON_EXPLICIT operator ValueType() const;
+Implicit type conversion between the JSON value and a compatible value. The call is realized by calling get(). See Notes for the meaning of JSON_EXPLICIT.
ValueTypecopy of the JSON value, converted to ValueType
Depends on what json_serializer<ValueType> from_json() method throws
Linear in the size of the JSON value.
Definition of JSON_EXPLICIT
By default JSON_EXPLICIT is defined to the empty string, so the signature is:
template<typename ValueType>
+operator ValueType() const;
+If JSON_USE_IMPLICIT_CONVERSIONS is set to 0, JSON_EXPLICIT is defined to explicit:
template<typename ValueType>
+explicit operator ValueType() const;
+That is, implicit conversions can be switched off by defining JSON_USE_IMPLICIT_CONVERSIONS to 0.
Future behavior change
Implicit conversions will be switched off by default in the next major release of the library. That is, JSON_EXPLICIT will be set to explicit by default.
You can prepare existing code by already defining JSON_USE_IMPLICIT_CONVERSIONS to 0 and replace any implicit conversions with calls to get.
The example below shows several conversions from JSON values to other types. There are a few things to note: (1) Floating-point numbers can be converted to integers, (2) A JSON array can be converted to a standard std::vector<short>, (3) A JSON object can be converted to C++ associative containers such as std::unordered_map<std::string, json>.
#include <iostream>
+#include <unordered_map>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create a JSON value with different types
+ json json_types =
+ {
+ {"boolean", true},
+ {
+ "number", {
+ {"integer", 42},
+ {"floating-point", 17.23}
+ }
+ },
+ {"string", "Hello, world!"},
+ {"array", {1, 2, 3, 4, 5}},
+ {"null", nullptr}
+ };
+
+ // use implicit conversions
+ bool v1 = json_types["boolean"];
+ int v2 = json_types["number"]["integer"];
+ short v3 = json_types["number"]["integer"];
+ float v4 = json_types["number"]["floating-point"];
+ int v5 = json_types["number"]["floating-point"];
+ std::string v6 = json_types["string"];
+ std::vector<short> v7 = json_types["array"];
+ std::unordered_map<std::string, json> v8 = json_types;
+
+ // print the conversion results
+ std::cout << v1 << '\n';
+ std::cout << v2 << ' ' << v3 << '\n';
+ std::cout << v4 << ' ' << v5 << '\n';
+ std::cout << v6 << '\n';
+
+ for (auto i : v7)
+ {
+ std::cout << i << ' ';
+ }
+ std::cout << "\n\n";
+
+ for (auto i : v8)
+ {
+ std::cout << i.first << ": " << i.second << '\n';
+ }
+
+ // example for an exception
+ try
+ {
+ bool v1 = json_types["string"];
+ }
+ catch (json::type_error& e)
+ {
+ std::cout << e.what() << '\n';
+ }
+}
+Output:
1
+42 42
+17.23 17
+Hello, world!
+1 2 3 4 5
+
+string: "Hello, world!"
+number: {"floating-point":17.23,"integer":42}
+null: null
+boolean: true
+array: [1,2,3,4,5]
+[json.exception.type_error.302] type must be boolean, but is string
+JSON_EXPLICIT/JSON_USE_IMPLICIT_CONVERSIONS added in version 3.9.0.// until C++20
+bool operator==(const_reference lhs, const_reference rhs) noexcept; // (1)
+
+template<typename ScalarType>
+bool operator==(const_reference lhs, const ScalarType rhs) noexcept; // (2)
+
+template<typename ScalarType>
+bool operator==(ScalarType lhs, const const_reference rhs) noexcept; // (2)
+
+// since C++20
+class basic_json {
+ bool operator==(const_reference rhs) const noexcept; // (1)
+
+ template<typename ScalarType>
+ bool operator==(ScalarType rhs) const noexcept; // (2)
+};
+Compares two JSON values for equality according to the following rules:
operator==.Compares a JSON value and a scalar or a scalar and a JSON value for equality by converting the scalar to a JSON value and comparing both JSON values according to 1.
ScalarTypestd::is_scalar<ScalarType>::valuelhs (in)rhs (in)whether the values lhs/*this and rhs are equal
No-throw guarantee: this function never throws exceptions.
Linear.
Comparing special values
NaN values are unordered within the domain of numbers. The following comparisons all yield false:NaN with itself.NaN with another NaN.NaN and any other number.null values are all equal.Comparing floating-point numbers
Floating-point numbers inside JSON values numbers are compared with json::number_float_t::operator== which is double::operator== by default. To compare floating-point while respecting an epsilon, an alternative comparison function could be used, for instance
template<typename T, typename = typename std::enable_if<std::is_floating_point<T>::value, T>::type>
+inline bool is_same(T a, T b, T epsilon = std::numeric_limits<T>::epsilon()) noexcept
+{
+ return std::abs(a - b) <= epsilon;
+}
+Or you can self-defined operator equal function like this:
bool my_equal(const_reference lhs, const_reference rhs)
+{
+ const auto lhs_type lhs.type();
+ const auto rhs_type rhs.type();
+ if (lhs_type == rhs_type)
+ {
+ switch(lhs_type)
+ // self_defined case
+ case value_t::number_float:
+ return std::abs(lhs - rhs) <= std::numeric_limits<float>::epsilon();
+ // other cases remain the same with the original
+ ...
+ }
+...
+}
+Comparing different basic_json specializations
Comparing different basic_json specializations can have surprising effects. For instance, the result of comparing the JSON objects
{
+ "version": 1,
+ "type": "integer"
+}
+and
{
+ "type": "integer",
+ "version": 1
+}
+depends on whether nlohmann::json or nlohmann::ordered_json is used:
#include <iostream>
+#include <iomanip>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ nlohmann::json uj1 = {{"version", 1}, {"type", "integer"}};
+ nlohmann::json uj2 = {{"type", "integer"}, {"version", 1}};
+
+ nlohmann::ordered_json oj1 = {{"version", 1}, {"type", "integer"}};
+ nlohmann::ordered_json oj2 = {{"type", "integer"}, {"version", 1}};
+
+ std::cout << std::boolalpha << (uj1 == uj2) << '\n' << (oj1 == oj2) << std::endl;
+}
+Output:
true
+false
+The example demonstrates comparing several JSON types.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create several JSON values
+ json array_1 = {1, 2, 3};
+ json array_2 = {1, 2, 4};
+ json object_1 = {{"A", "a"}, {"B", "b"}};
+ json object_2 = {{"B", "b"}, {"A", "a"}};
+ json number_1 = 17;
+ json number_2 = 17.000000000000001L;
+ json string_1 = "foo";
+ json string_2 = "bar";
+
+ // output values and comparisons
+ std::cout << std::boolalpha;
+ std::cout << array_1 << " == " << array_2 << " " << (array_1 == array_2) << '\n';
+ std::cout << object_1 << " == " << object_2 << " " << (object_1 == object_2) << '\n';
+ std::cout << number_1 << " == " << number_2 << " " << (number_1 == number_2) << '\n';
+ std::cout << string_1 << " == " << string_2 << " " << (string_1 == string_2) << '\n';
+}
+Output:
[1,2,3] == [1,2,4] false
+{"A":"a","B":"b"} == {"A":"a","B":"b"} true
+17 == 17.0 true
+"foo" == "bar" false
+The example demonstrates comparing several JSON types against the null pointer (JSON null).
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create several JSON values
+ json array = {1, 2, 3};
+ json object = {{"A", "a"}, {"B", "b"}};
+ json number = 17;
+ json string = "foo";
+ json null;
+
+ // output values and comparisons
+ std::cout << std::boolalpha;
+ std::cout << array << " == nullptr " << (array == nullptr) << '\n';
+ std::cout << object << " == nullptr " << (object == nullptr) << '\n';
+ std::cout << number << " == nullptr " << (number == nullptr) << '\n';
+ std::cout << string << " == nullptr " << (string == nullptr) << '\n';
+ std::cout << null << " == nullptr " << (null == nullptr) << '\n';
+}
+Output:
[1,2,3] == nullptr false
+{"A":"a","B":"b"} == nullptr false
+17 == nullptr false
+"foo" == nullptr false
+null == nullptr true
+// until C++20
+bool operator>=(const_reference lhs, const_reference rhs) noexcept; // (1)
+
+template<typename ScalarType>
+bool operator>=(const_reference lhs, const ScalarType rhs) noexcept; // (2)
+
+template<typename ScalarType>
+bool operator>=(ScalarType lhs, const const_reference rhs) noexcept; // (2)
+Compares whether one JSON value lhs is greater than or equal to another JSON value rhs according to the following rules:
false if (1) either operand is discarded, or (2) either operand is NaN and the other operand is either NaN or any other number.!(lhs < rhs) (see operator<).Compares whether a JSON value is greater than or equal to a scalar or a scalar is greater than or equal to a JSON value by converting the scalar to a JSON value and comparing both JSON values according to 1.
ScalarTypestd::is_scalar<ScalarType>::valuelhs (in)rhs (in)whether lhs is less than or equal to rhs
No-throw guarantee: this function never throws exceptions.
Linear.
Comparing NaN
NaN values are unordered within the domain of numbers. The following comparisons all yield false: 1. Comparing a NaN with itself. 2. Comparing a NaN with another NaN. 3. Comparing a NaN and any other number.
Operator overload resolution
Since C++20 overload resolution will consider the rewritten candidate generated from operator<=>.
The example demonstrates comparing several JSON types.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create several JSON values
+ json array_1 = {1, 2, 3};
+ json array_2 = {1, 2, 4};
+ json object_1 = {{"A", "a"}, {"B", "b"}};
+ json object_2 = {{"B", "b"}, {"A", "a"}};
+ json number_1 = 17;
+ json number_2 = 17.0000000000001L;
+ json string_1 = "foo";
+ json string_2 = "bar";
+
+ // output values and comparisons
+ std::cout << std::boolalpha;
+ std::cout << array_1 << " >= " << array_2 << " " << (array_1 >= array_2) << '\n';
+ std::cout << object_1 << " >= " << object_2 << " " << (object_1 >= object_2) << '\n';
+ std::cout << number_1 << " >= " << number_2 << " " << (number_1 >= number_2) << '\n';
+ std::cout << string_1 << " >= " << string_2 << " " << (string_1 >= string_2) << '\n';
+}
+Output:
[1,2,3] >= [1,2,4] false
+{"A":"a","B":"b"} >= {"A":"a","B":"b"} true
+17 >= 17.0000000000001 false
+"foo" >= "bar" true
+// until C++20
+bool operator>(const_reference lhs, const_reference rhs) noexcept; // (1)
+
+template<typename ScalarType>
+bool operator>(const_reference lhs, const ScalarType rhs) noexcept; // (2)
+
+template<typename ScalarType>
+bool operator>(ScalarType lhs, const const_reference rhs) noexcept; // (2)
+Compares whether one JSON value lhs is greater than another JSON value rhs according to the following rules:
false if (1) either operand is discarded, or (2) either operand is NaN and the other operand is either NaN or any other number.!(lhs <= rhs) (see operator<=).Compares wether a JSON value is greater than a scalar or a scalar is greater than a JSON value by converting the scalar to a JSON value and comparing both JSON values according to 1.
ScalarTypestd::is_scalar<ScalarType>::valuelhs (in)rhs (in)whether lhs is greater than rhs
No-throw guarantee: this function never throws exceptions.
Linear.
Comparing NaN
NaN values are unordered within the domain of numbers. The following comparisons all yield false: 1. Comparing a NaN with itself. 2. Comparing a NaN with another NaN. 3. Comparing a NaN and any other number.
Operator overload resolution
Since C++20 overload resolution will consider the rewritten candidate generated from operator<=>.
The example demonstrates comparing several JSON types.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create several JSON values
+ json array_1 = {1, 2, 3};
+ json array_2 = {1, 2, 4};
+ json object_1 = {{"A", "a"}, {"B", "b"}};
+ json object_2 = {{"B", "b"}, {"A", "a"}};
+ json number_1 = 17;
+ json number_2 = 17.0000000000001L;
+ json string_1 = "foo";
+ json string_2 = "bar";
+
+ // output values and comparisons
+ std::cout << std::boolalpha;
+ std::cout << array_1 << " > " << array_2 << " " << (array_1 > array_2) << '\n';
+ std::cout << object_1 << " > " << object_2 << " " << (object_1 > object_2) << '\n';
+ std::cout << number_1 << " > " << number_2 << " " << (number_1 > number_2) << '\n';
+ std::cout << string_1 << " > " << string_2 << " " << (string_1 > string_2) << '\n';
+}
+Output:
[1,2,3] > [1,2,4] false
+{"A":"a","B":"b"} > {"A":"a","B":"b"} false
+17 > 17.0000000000001 false
+"foo" > "bar" true
+// until C++20
+bool operator<=(const_reference lhs, const_reference rhs) noexcept; // (1)
+
+template<typename ScalarType>
+bool operator<=(const_reference lhs, const ScalarType rhs) noexcept; // (2)
+
+template<typename ScalarType>
+bool operator<=(ScalarType lhs, const const_reference rhs) noexcept; // (2)
+Compares whether one JSON value lhs is less than or equal to another JSON value rhs according to the following rules:
false if (1) either operand is discarded, or (2) either operand is NaN and the other operand is either NaN or any other number.!(rhs < lhs) (see operator<).Compares wether a JSON value is less than or equal to a scalar or a scalar is less than or equal to a JSON value by converting the scalar to a JSON value and comparing both JSON values according to 1.
ScalarTypestd::is_scalar<ScalarType>::valuelhs (in)rhs (in)whether lhs is less than or equal to rhs
No-throw guarantee: this function never throws exceptions.
Linear.
Comparing NaN
NaN values are unordered within the domain of numbers. The following comparisons all yield false: 1. Comparing a NaN with itself. 2. Comparing a NaN with another NaN. 3. Comparing a NaN and any other number.
Operator overload resolution
Since C++20 overload resolution will consider the rewritten candidate generated from operator<=>.
The example demonstrates comparing several JSON types.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create several JSON values
+ json array_1 = {1, 2, 3};
+ json array_2 = {1, 2, 4};
+ json object_1 = {{"A", "a"}, {"B", "b"}};
+ json object_2 = {{"B", "b"}, {"A", "a"}};
+ json number_1 = 17;
+ json number_2 = 17.0000000000001L;
+ json string_1 = "foo";
+ json string_2 = "bar";
+
+ // output values and comparisons
+ std::cout << std::boolalpha;
+ std::cout << array_1 << " <= " << array_2 << " " << (array_1 <= array_2) << '\n';
+ std::cout << object_1 << " <= " << object_2 << " " << (object_1 <= object_2) << '\n';
+ std::cout << number_1 << " <= " << number_2 << " " << (number_1 <= number_2) << '\n';
+ std::cout << string_1 << " <= " << string_2 << " " << (string_1 <= string_2) << '\n';
+}
+Output:
[1,2,3] <= [1,2,4] true
+{"A":"a","B":"b"} <= {"A":"a","B":"b"} true
+17 <= 17.0000000000001 true
+"foo" <= "bar" false
+// until C++20
+bool operator<(const_reference lhs, const_reference rhs) noexcept; // (1)
+
+template<typename ScalarType>
+bool operator<(const_reference lhs, const ScalarType rhs) noexcept; // (2)
+
+template<typename ScalarType>
+bool operator<(ScalarType lhs, const const_reference rhs) noexcept; // (2)
+Compares whether one JSON value lhs is less than another JSON value rhs according to the following rules:
false.operator<.lhs and rhs have different types, the values are ignored and the order of the types is considered, which is:Compares wether a JSON value is less than a scalar or a scalar is less than a JSON value by converting the scalar to a JSON value and comparing both JSON values according to 1.
ScalarTypestd::is_scalar<ScalarType>::valuelhs (in)rhs (in)whether lhs is less than rhs
No-throw guarantee: this function never throws exceptions.
Linear.
Comparing NaN
NaN values are unordered within the domain of numbers. The following comparisons all yield false: 1. Comparing a NaN with itself. 2. Comparing a NaN with another NaN. 3. Comparing a NaN and any other number.
Operator overload resolution
Since C++20 overload resolution will consider the rewritten candidate generated from operator<=>.
The example demonstrates comparing several JSON types.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create several JSON values
+ json array_1 = {1, 2, 3};
+ json array_2 = {1, 2, 4};
+ json object_1 = {{"A", "a"}, {"B", "b"}};
+ json object_2 = {{"B", "b"}, {"A", "a"}};
+ json number_1 = 17;
+ json number_2 = 17.0000000000001L;
+ json string_1 = "foo";
+ json string_2 = "bar";
+
+ // output values and comparisons
+ std::cout << std::boolalpha;
+ std::cout << array_1 << " == " << array_2 << " " << (array_1 < array_2) << '\n';
+ std::cout << object_1 << " == " << object_2 << " " << (object_1 < object_2) << '\n';
+ std::cout << number_1 << " == " << number_2 << " " << (number_1 < number_2) << '\n';
+ std::cout << string_1 << " == " << string_2 << " " << (string_1 < string_2) << '\n';
+}
+Output:
[1,2,3] == [1,2,4] true
+{"A":"a","B":"b"} == {"A":"a","B":"b"} false
+17 == 17.0000000000001 true
+"foo" == "bar" false
+// until C++20
+bool operator!=(const_reference lhs, const_reference rhs) noexcept; // (1)
+
+template<typename ScalarType>
+bool operator!=(const_reference lhs, const ScalarType rhs) noexcept; // (2)
+
+template<typename ScalarType>
+bool operator!=(ScalarType lhs, const const_reference rhs) noexcept; // (2)
+
+// since C++20
+class basic_json {
+ bool operator!=(const_reference rhs) const noexcept; // (1)
+
+ template<typename ScalarType>
+ bool operator!=(ScalarType rhs) const noexcept; // (2)
+};
+Compares two JSON values for inequality according to the following rules:
false if (1) either operand is discarded, or (2) either operand is NaN and the other operand is either NaN or any other number.!(lhs == rhs) (until C++20) or !(*this == rhs) (since C++20).Compares a JSON value and a scalar or a scalar and a JSON value for inequality by converting the scalar to a JSON value and comparing both JSON values according to 1.
ScalarTypestd::is_scalar<ScalarType>::valuelhs (in)rhs (in)whether the values lhs/*this and rhs are not equal
No-throw guarantee: this function never throws exceptions.
Linear.
Comparing NaN
NaN values are unordered within the domain of numbers. The following comparisons all yield false: 1. Comparing a NaN with itself. 2. Comparing a NaN with another NaN. 3. Comparing a NaN and any other number.
The example demonstrates comparing several JSON types.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create several JSON values
+ json array_1 = {1, 2, 3};
+ json array_2 = {1, 2, 4};
+ json object_1 = {{"A", "a"}, {"B", "b"}};
+ json object_2 = {{"B", "b"}, {"A", "a"}};
+ json number_1 = 17;
+ json number_2 = 17.000000000000001L;
+ json string_1 = "foo";
+ json string_2 = "bar";
+
+ // output values and comparisons
+ std::cout << std::boolalpha;
+ std::cout << array_1 << " != " << array_2 << " " << (array_1 != array_2) << '\n';
+ std::cout << object_1 << " != " << object_2 << " " << (object_1 != object_2) << '\n';
+ std::cout << number_1 << " != " << number_2 << " " << (number_1 != number_2) << '\n';
+ std::cout << string_1 << " != " << string_2 << " " << (string_1 != string_2) << '\n';
+}
+Output:
[1,2,3] != [1,2,4] true
+{"A":"a","B":"b"} != {"A":"a","B":"b"} false
+17 != 17.0 false
+"foo" != "bar" true
+The example demonstrates comparing several JSON types against the null pointer (JSON null).
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create several JSON values
+ json array = {1, 2, 3};
+ json object = {{"A", "a"}, {"B", "b"}};
+ json number = 17;
+ json string = "foo";
+ json null;
+
+ // output values and comparisons
+ std::cout << std::boolalpha;
+ std::cout << array << " != nullptr " << (array != nullptr) << '\n';
+ std::cout << object << " != nullptr " << (object != nullptr) << '\n';
+ std::cout << number << " != nullptr " << (number != nullptr) << '\n';
+ std::cout << string << " != nullptr " << (string != nullptr) << '\n';
+ std::cout << null << " != nullptr " << (null != nullptr) << '\n';
+}
+Output:
[1,2,3] != nullptr true
+{"A":"a","B":"b"} != nullptr true
+17 != nullptr true
+"foo" != nullptr true
+null != nullptr false
+// since C++20
+class basic_json {
+ std::partial_ordering operator<=>(const_reference rhs) const noexcept; // (1)
+
+ template<typename ScalarType>
+ std::partial_ordering operator<=>(const ScalarType rhs) const noexcept; // (2)
+};
+3-way compares two JSON values producing a result of type std::partial_ordering according to the following rules:
std::partial_ordering::unordered if either value is discarded.operator<=>.operator<=>. For instance, comparing an integer and a floating-point value will 3-way compare the first value converted to floating-point with the second value.value_t).3-way compares a JSON value and a scalar or a scalar and a JSON value by converting the scalar to a JSON value and 3-way comparing both JSON values (see 1).
ScalarTypestd::is_scalar<ScalarType>::valuerhs (in)the std::partial_ordering of the 3-way comparison of *this and rhs
No-throw guarantee: this function never throws exceptions.
Linear.
Comparing NaN
NaN values are unordered within the domain of numbers. The following comparisons all yield std::partial_ordering::unordered:NaN with itself.NaN with another NaN.NaN and any other number.The example demonstrates comparing several JSON values.
#include <compare>
+#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+const char* to_string(const std::partial_ordering& po)
+{
+ if (std::is_lt(po))
+ {
+ return "less";
+ }
+ else if (std::is_gt(po))
+ {
+ return "greater";
+ }
+ else if (std::is_eq(po))
+ {
+ return "equivalent";
+ }
+ return "unordered";
+}
+
+int main()
+{
+ // create several JSON values
+ json array_1 = {1, 2, 3};
+ json array_2 = {1, 2, 4};
+ json object_1 = {{"A", "a"}, {"B", "b"}};
+ json object_2 = {{"B", "b"}, {"A", "a"}};
+ json number = 17;
+ json string = "foo";
+ json discarded = json(json::value_t::discarded);
+
+
+ // output values and comparisons
+ std::cout << array_1 << " <=> " << array_2 << " := " << to_string(array_1 <=> array_2) << '\n'; // *NOPAD*
+ std::cout << object_1 << " <=> " << object_2 << " := " << to_string(object_1 <=> object_2) << '\n'; // *NOPAD*
+ std::cout << string << " <=> " << number << " := " << to_string(string <=> number) << '\n'; // *NOPAD*
+ std::cout << string << " <=> " << discarded << " := " << to_string(string <=> discarded) << '\n'; // *NOPAD*
+}
+Output:
[1,2,3] <=> [1,2,4] := less
+{"A":"a","B":"b"} <=> {"A":"a","B":"b"} := equivalent
+"foo" <=> 17 := greater
+"foo" <=> <discarded> := unordered
+The example demonstrates comparing several JSON values and scalars.
#include <compare>
+#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+const char* to_string(const std::partial_ordering& po)
+{
+ if (std::is_lt(po))
+ {
+ return "less";
+ }
+ else if (std::is_gt(po))
+ {
+ return "greater";
+ }
+ else if (std::is_eq(po))
+ {
+ return "equivalent";
+ }
+ return "unordered";
+}
+
+int main()
+{
+ using float_limits = std::numeric_limits<json::number_float_t>;
+ constexpr auto nan = float_limits::quiet_NaN();
+
+ // create several JSON values
+ json boolean = false;
+ json number = 17;
+ json string = "17";
+
+
+ // output values and comparisons
+ std::cout << std::boolalpha << std::fixed;
+ std::cout << boolean << " <=> " << true << " := " << to_string(boolean <=> true) << '\n'; // *NOPAD*
+ std::cout << number << " <=> " << 17.0 << " := " << to_string(number <=> 17.0) << '\n'; // *NOPAD*
+ std::cout << number << " <=> " << nan << " := " << to_string(number <=> nan) << '\n'; // *NOPAD*
+ std::cout << string << " <=> " << 17 << " := " << to_string(string <=> 17) << '\n'; // *NOPAD*
+}
+Output:
false <=> true := less
+17 <=> 17.000000 := equivalent
+17 <=> nan := unordered
+"17" <=> 17 := greater
+constexpr operator value_t() const noexcept;
+Return the type of the JSON value as a value from the value_t enumeration.
the type of the JSON value
| Value type | return value |
|---|---|
null | value_t::null |
| boolean | value_t::boolean |
| string | value_t::string |
| number (integer) | value_t::number_integer |
| number (unsigned integer) | value_t::number_unsigned |
| number (floating-point) | value_t::number_float |
| object | value_t::object |
| array | value_t::array |
| binary | value_t::binary |
| discarded | value_t::discarded |
No-throw guarantee: this member function never throws exceptions.
Constant.
The following code exemplifies operator value_t() for all JSON types.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create JSON values
+ json j_null;
+ json j_boolean = true;
+ json j_number_integer = -17;
+ json j_number_unsigned = 42u;
+ json j_number_float = 23.42;
+ json j_object = {{"one", 1}, {"two", 2}};
+ json j_array = {1, 2, 4, 8, 16};
+ json j_string = "Hello, world";
+
+ // call operator value_t()
+ json::value_t t_null = j_null;
+ json::value_t t_boolean = j_boolean;
+ json::value_t t_number_integer = j_number_integer;
+ json::value_t t_number_unsigned = j_number_unsigned;
+ json::value_t t_number_float = j_number_float;
+ json::value_t t_object = j_object;
+ json::value_t t_array = j_array;
+ json::value_t t_string = j_string;
+
+ // print types
+ std::cout << std::boolalpha;
+ std::cout << (t_null == json::value_t::null) << '\n';
+ std::cout << (t_boolean == json::value_t::boolean) << '\n';
+ std::cout << (t_number_integer == json::value_t::number_integer) << '\n';
+ std::cout << (t_number_unsigned == json::value_t::number_unsigned) << '\n';
+ std::cout << (t_number_float == json::value_t::number_float) << '\n';
+ std::cout << (t_object == json::value_t::object) << '\n';
+ std::cout << (t_array == json::value_t::array) << '\n';
+ std::cout << (t_string == json::value_t::string) << '\n';
+}
+Output:
true
+true
+true
+true
+true
+true
+true
+true
+class other_error : public exception;
+This exception is thrown in case of errors that cannot be classified with the other exception types.
Exceptions have ids 5xx (see list of other errors).
The following code shows how a other_error exception can be caught.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+using namespace nlohmann::literals;
+
+int main()
+{
+ try
+ {
+ // executing a failing JSON Patch operation
+ json value = R"({
+ "best_biscuit": {
+ "name": "Oreo"
+ }
+ })"_json;
+ json patch = R"([{
+ "op": "test",
+ "path": "/best_biscuit/name",
+ "value": "Choco Leibniz"
+ }])"_json;
+ value.patch(patch);
+ }
+ catch (json::other_error& e)
+ {
+ // output exception information
+ std::cout << "message: " << e.what() << '\n'
+ << "exception id: " << e.id << std::endl;
+ }
+}
+Output:
message: [json.exception.other_error.501] unsuccessful: {"op":"test","path":"/best_biscuit/name","value":"Choco Leibniz"}
+exception id: 501
+parse_error for exceptions indicating a parse errorinvalid_iterator for exceptions indicating errors with iteratorstype_error for exceptions indicating executing a member function with a wrong typeout_of_range for exceptions indicating access out of the defined rangeclass out_of_range : public exception;
+This exception is thrown in case a library function is called on an input parameter that exceeds the expected range, for instance in case of array indices or nonexisting object keys.
Exceptions have ids 4xx (see list of out-of-range errors).
The following code shows how a out_of_range exception can be caught.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ try
+ {
+ // calling at() for an invalid index
+ json j = {1, 2, 3, 4};
+ j.at(4) = 10;
+ }
+ catch (json::out_of_range& e)
+ {
+ // output exception information
+ std::cout << "message: " << e.what() << '\n'
+ << "exception id: " << e.id << std::endl;
+ }
+}
+Output:
message: [json.exception.out_of_range.401] array index 4 is out of range
+exception id: 401
+parse_error for exceptions indicating a parse errorinvalid_iterator for exceptions indicating errors with iteratorstype_error for exceptions indicating executing a member function with a wrong typeother_error for exceptions indicating other library errors// (1)
+template<typename InputType>
+static basic_json parse(InputType&& i,
+ const parser_callback_t cb = nullptr,
+ const bool allow_exceptions = true,
+ const bool ignore_comments = false);
+
+// (2)
+template<typename IteratorType>
+static basic_json parse(IteratorType first, IteratorType last,
+ const parser_callback_t cb = nullptr,
+ const bool allow_exceptions = true,
+ const bool ignore_comments = false);
+Deserialize from a pair of character iterators
The value_type of the iterator must be an integral type with size of 1, 2 or 4 bytes, which will be interpreted respectively as UTF-8, UTF-16 and UTF-32.
InputTypeA compatible input, for instance:
std::istream objectFILE pointer (must not be null)std::stringobj for which begin(obj) and end(obj) produces a valid pair of iterators.IteratorTypea compatible iterator type, for instance.
std::string::iterator or std::vector<std::uint8_t>::iteratorptr and ptr + leni (in)cb (in)parser_callback_t which is used to control the deserialization by filtering unwanted values (optional)allow_exceptions (in)true by default)ignore_comments (in)true) or yield a parse error (false); (optional, false by default)first (in)last (in)Deserialized JSON value; in case of a parse error and allow_exceptions set to false, the return value will be value_t::discarded. The latter can be checked with is_discarded.
Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
parse_error.101 in case of an unexpected token.parse_error.102 if to_unicode fails or surrogate error.parse_error.103 if to_unicode fails.Linear in the length of the input. The parser is a predictive LL(1) parser. The complexity can be higher if the parser callback function cb or reading from (1) the input i or (2) the iterator range [first, last] has a super-linear complexity.
(1) A UTF-8 byte order mark is silently ignored.
Runtime assertion
The precondition that a passed FILE pointer must not be null is enforced with a runtime assertion.
The example below demonstrates the parse() function reading from an array.
#include <iostream>
+#include <iomanip>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // a JSON text
+ char text[] = R"(
+ {
+ "Image": {
+ "Width": 800,
+ "Height": 600,
+ "Title": "View from 15th Floor",
+ "Thumbnail": {
+ "Url": "http://www.example.com/image/481989943",
+ "Height": 125,
+ "Width": 100
+ },
+ "Animated" : false,
+ "IDs": [116, 943, 234, 38793]
+ }
+ }
+ )";
+
+ // parse and serialize JSON
+ json j_complete = json::parse(text);
+ std::cout << std::setw(4) << j_complete << "\n\n";
+}
+Output:
{
+ "Image": {
+ "Animated": false,
+ "Height": 600,
+ "IDs": [
+ 116,
+ 943,
+ 234,
+ 38793
+ ],
+ "Thumbnail": {
+ "Height": 125,
+ "Url": "http://www.example.com/image/481989943",
+ "Width": 100
+ },
+ "Title": "View from 15th Floor",
+ "Width": 800
+ }
+}
+The example below demonstrates the parse() function with and without callback function.
#include <iostream>
+#include <iomanip>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // a JSON text
+ auto text = R"(
+ {
+ "Image": {
+ "Width": 800,
+ "Height": 600,
+ "Title": "View from 15th Floor",
+ "Thumbnail": {
+ "Url": "http://www.example.com/image/481989943",
+ "Height": 125,
+ "Width": 100
+ },
+ "Animated" : false,
+ "IDs": [116, 943, 234, 38793]
+ }
+ }
+ )";
+
+ // parse and serialize JSON
+ json j_complete = json::parse(text);
+ std::cout << std::setw(4) << j_complete << "\n\n";
+
+
+ // define parser callback
+ json::parser_callback_t cb = [](int depth, json::parse_event_t event, json & parsed)
+ {
+ // skip object elements with key "Thumbnail"
+ if (event == json::parse_event_t::key and parsed == json("Thumbnail"))
+ {
+ return false;
+ }
+ else
+ {
+ return true;
+ }
+ };
+
+ // parse (with callback) and serialize JSON
+ json j_filtered = json::parse(text, cb);
+ std::cout << std::setw(4) << j_filtered << '\n';
+}
+Output:
{
+ "Image": {
+ "Animated": false,
+ "Height": 600,
+ "IDs": [
+ 116,
+ 943,
+ 234,
+ 38793
+ ],
+ "Thumbnail": {
+ "Height": 125,
+ "Url": "http://www.example.com/image/481989943",
+ "Width": 100
+ },
+ "Title": "View from 15th Floor",
+ "Width": 800
+ }
+}
+
+{
+ "Image": {
+ "Animated": false,
+ "Height": 600,
+ "IDs": [
+ 116,
+ 943,
+ 234,
+ 38793
+ ],
+ "Title": "View from 15th Floor",
+ "Width": 800
+ }
+}
+The example below demonstrates the parse() function with and without callback function.
#include <iostream>
+#include <iomanip>
+#include <sstream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // a JSON text
+ auto text = R"(
+ {
+ "Image": {
+ "Width": 800,
+ "Height": 600,
+ "Title": "View from 15th Floor",
+ "Thumbnail": {
+ "Url": "http://www.example.com/image/481989943",
+ "Height": 125,
+ "Width": 100
+ },
+ "Animated" : false,
+ "IDs": [116, 943, 234, 38793]
+ }
+ }
+ )";
+
+ // fill a stream with JSON text
+ std::stringstream ss;
+ ss << text;
+
+ // parse and serialize JSON
+ json j_complete = json::parse(ss);
+ std::cout << std::setw(4) << j_complete << "\n\n";
+
+
+ // define parser callback
+ json::parser_callback_t cb = [](int depth, json::parse_event_t event, json & parsed)
+ {
+ // skip object elements with key "Thumbnail"
+ if (event == json::parse_event_t::key and parsed == json("Thumbnail"))
+ {
+ return false;
+ }
+ else
+ {
+ return true;
+ }
+ };
+
+ // fill a stream with JSON text
+ ss.clear();
+ ss << text;
+
+ // parse (with callback) and serialize JSON
+ json j_filtered = json::parse(ss, cb);
+ std::cout << std::setw(4) << j_filtered << '\n';
+}
+Output:
{
+ "Image": {
+ "Animated": false,
+ "Height": 600,
+ "IDs": [
+ 116,
+ 943,
+ 234,
+ 38793
+ ],
+ "Thumbnail": {
+ "Height": 125,
+ "Url": "http://www.example.com/image/481989943",
+ "Width": 100
+ },
+ "Title": "View from 15th Floor",
+ "Width": 800
+ }
+}
+
+{
+ "Image": {
+ "Animated": false,
+ "Height": 600,
+ "IDs": [
+ 116,
+ 943,
+ 234,
+ 38793
+ ],
+ "Title": "View from 15th Floor",
+ "Width": 800
+ }
+}
+The example below demonstrates the parse() function reading from a contiguous container.
#include <iostream>
+#include <iomanip>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // a JSON text given as std::vector
+ std::vector<std::uint8_t> text = {'[', '1', ',', '2', ',', '3', ']', '\0'};
+
+ // parse and serialize JSON
+ json j_complete = json::parse(text);
+ std::cout << std::setw(4) << j_complete << "\n\n";
+}
+Output:
[
+ 1,
+ 2,
+ 3
+]
+The example below demonstrates the parse() function reading from a string that is not null-terminated.
#include <iostream>
+#include <iomanip>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // a JSON text given as string that is not null-terminated
+ const char* ptr = "[1,2,3]another value";
+
+ // parse and serialize JSON
+ json j_complete = json::parse(ptr, ptr + 7);
+ std::cout << std::setw(4) << j_complete << "\n\n";
+}
+Output:
[
+ 1,
+ 2,
+ 3
+]
+The example below demonstrates the parse() function reading from an iterator pair.
#include <iostream>
+#include <iomanip>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // a JSON text given an input with other values
+ std::vector<std::uint8_t> input = {'[', '1', ',', '2', ',', '3', ']', 'o', 't', 'h', 'e', 'r'};
+
+ // parse and serialize JSON
+ json j_complete = json::parse(input.begin(), input.begin() + 7);
+ std::cout << std::setw(4) << j_complete << "\n\n";
+}
+Output:
[
+ 1,
+ 2,
+ 3
+]
+allow_exceptions parameterThe example below demonstrates the effect of the allow_exceptions parameter in the ´parse()` function.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // an invalid JSON text
+ std::string text = R"(
+ {
+ "key": "value without closing quotes
+ }
+ )";
+
+ // parse with exceptions
+ try
+ {
+ json j = json::parse(text);
+ }
+ catch (json::parse_error& e)
+ {
+ std::cout << e.what() << std::endl;
+ }
+
+ // parse without exceptions
+ json j = json::parse(text, nullptr, false);
+
+ if (j.is_discarded())
+ {
+ std::cout << "the input is invalid JSON" << std::endl;
+ }
+ else
+ {
+ std::cout << "the input is valid JSON: " << j << std::endl;
+ }
+}
+Output:
[json.exception.parse_error.101] parse error at line 4, column 0: syntax error while parsing value - invalid string: control character U+000A (LF) must be escaped to \u000A or \n; last read: '"value without closing quotes<U+000A>'
+the input is invalid JSON
+ignore_comments added in version 3.9.0.Deprecation
Overload (2) replaces calls to parse with a pair of iterators as their first parameter which has been deprecated in version 3.8.0. This overload will be removed in version 4.0.0. Please replace all calls like parse({ptr, ptr+len}, ...); with parse(ptr, ptr+len, ...);.
You should be warned by your compiler with a -Wdeprecated-declarations warning if you are using a deprecated function.
class parse_error : public exception;
+This exception is thrown by the library when a parse error occurs. Parse errors can occur during the deserialization of JSON text, BSON, CBOR, MessagePack, UBJSON, as well as when using JSON Patch.
Member byte holds the byte index of the last read character in the input file (see note below).
Exceptions have ids 1xx (see list of parse errors).
For an input with n bytes, 1 is the index of the first character and n+1 is the index of the terminating null byte or the end of file. This also holds true when reading a byte vector for binary formats.
The following code shows how a parse_error exception can be caught.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ try
+ {
+ // parsing input with a syntax error
+ json::parse("[1,2,3,]");
+ }
+ catch (json::parse_error& e)
+ {
+ // output exception information
+ std::cout << "message: " << e.what() << '\n'
+ << "exception id: " << e.id << '\n'
+ << "byte position of error: " << e.byte << std::endl;
+ }
+}
+Output:
message: [json.exception.parse_error.101] parse error at line 1, column 8: syntax error while parsing value - unexpected ']'; expected '[', '{', or a literal
+exception id: 101
+byte position of error: 8
+invalid_iterator for exceptions indicating errors with iteratorstype_error for exceptions indicating executing a member function with a wrong typeout_of_range for exceptions indicating access out of the defined rangeother_error for exceptions indicating other library errorsenum class parse_event_t : std::uint8_t {
+ object_start,
+ object_end,
+ array_start,
+ array_end,
+ key,
+ value
+};
+The parser callback distinguishes the following events:
object_start: the parser read { and started to process a JSON objectkey: the parser read a key of a value in an objectobject_end: the parser read } and finished processing a JSON objectarray_start: the parser read [ and started to process a JSON arrayarray_end: the parser read ] and finished processing a JSON arrayvalue: the parser finished reading a JSON value
template<typename BasicJsonType>
+using parser_callback_t =
+ std::function<bool(int depth, parse_event_t event, BasicJsonType& parsed)>;
+With a parser callback function, the result of parsing a JSON text can be influenced. When passed to parse, it is called on certain events (passed as parse_event_t via parameter event) with a set recursion depth depth and context JSON value parsed. The return value of the callback function is a boolean indicating whether the element that emitted the callback shall be kept or not.
We distinguish six scenarios (determined by the event type) in which the callback function can be called. The following table describes the values of the parameters depth, event, and parsed.
parameter event | description | parameter depth | parameter parsed |
|---|---|---|---|
parse_event_t::object_start | the parser read { and started to process a JSON object | depth of the parent of the JSON object | a JSON value with type discarded |
parse_event_t::key | the parser read a key of a value in an object | depth of the currently parsed JSON object | a JSON string containing the key |
parse_event_t::object_end | the parser read } and finished processing a JSON object | depth of the parent of the JSON object | the parsed JSON object |
parse_event_t::array_start | the parser read [ and started to process a JSON array | depth of the parent of the JSON array | a JSON value with type discarded |
parse_event_t::array_end | the parser read ] and finished processing a JSON array | depth of the parent of the JSON array | the parsed JSON array |
parse_event_t::value | the parser finished reading a JSON value | depth of the value | the parsed JSON value |

Discarding a value (i.e., returning false) has different effects depending on the context in which function was called:
null. This case happens if the top-level element is skipped.depth (in)event (in)parse_event_t indicating the context in the callback function has been calledparsed (in, out)parse_event_t::key eventsWhether the JSON value which called the function during parsing should be kept (true) or not (false). In the latter case, it is either skipped completely or replaced by an empty discarded object.
The example below demonstrates the parse() function with and without callback function.
#include <iostream>
+#include <iomanip>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // a JSON text
+ auto text = R"(
+ {
+ "Image": {
+ "Width": 800,
+ "Height": 600,
+ "Title": "View from 15th Floor",
+ "Thumbnail": {
+ "Url": "http://www.example.com/image/481989943",
+ "Height": 125,
+ "Width": 100
+ },
+ "Animated" : false,
+ "IDs": [116, 943, 234, 38793]
+ }
+ }
+ )";
+
+ // parse and serialize JSON
+ json j_complete = json::parse(text);
+ std::cout << std::setw(4) << j_complete << "\n\n";
+
+
+ // define parser callback
+ json::parser_callback_t cb = [](int depth, json::parse_event_t event, json & parsed)
+ {
+ // skip object elements with key "Thumbnail"
+ if (event == json::parse_event_t::key and parsed == json("Thumbnail"))
+ {
+ return false;
+ }
+ else
+ {
+ return true;
+ }
+ };
+
+ // parse (with callback) and serialize JSON
+ json j_filtered = json::parse(text, cb);
+ std::cout << std::setw(4) << j_filtered << '\n';
+}
+Output:
{
+ "Image": {
+ "Animated": false,
+ "Height": 600,
+ "IDs": [
+ 116,
+ 943,
+ 234,
+ 38793
+ ],
+ "Thumbnail": {
+ "Height": 125,
+ "Url": "http://www.example.com/image/481989943",
+ "Width": 100
+ },
+ "Title": "View from 15th Floor",
+ "Width": 800
+ }
+}
+
+{
+ "Image": {
+ "Animated": false,
+ "Height": 600,
+ "IDs": [
+ 116,
+ 943,
+ 234,
+ 38793
+ ],
+ "Title": "View from 15th Floor",
+ "Width": 800
+ }
+}
+basic_json patch(const basic_json& json_patch) const;
+JSON Patch defines a JSON document structure for expressing a sequence of operations to apply to a JSON document. With this function, a JSON Patch is applied to the current JSON value by executing all operations from the patch.
json_patch (in)patched document
Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
parse_error.104 if the JSON patch does not consist of an array of objects.parse_error.105 if the JSON patch is malformed (e.g., mandatory attributes are missing); example: "operation add must have member path".out_of_range.401 if an array index is out of range.out_of_range.403 if a JSON pointer inside the patch could not be resolved successfully in the current JSON value; example: "key baz not found".out_of_range.405 if JSON pointer has no parent ("add", "remove", "move")out_of_range.501 if "test" operation was unsuccessful.Linear in the size of the JSON value and the length of the JSON patch. As usually only a fraction of the JSON value is affected by the patch, the complexity can usually be neglected.
The application of a patch is atomic: Either all operations succeed and the patched document is returned or an exception is thrown. In any case, the original value is not changed: the patch is applied to a copy of the value.
The following code shows how a JSON patch is applied to a value.
#include <iostream>
+#include <iomanip>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+using namespace nlohmann::literals;
+
+int main()
+{
+ // the original document
+ json doc = R"(
+ {
+ "baz": "qux",
+ "foo": "bar"
+ }
+ )"_json;
+
+ // the patch
+ json patch = R"(
+ [
+ { "op": "replace", "path": "/baz", "value": "boo" },
+ { "op": "add", "path": "/hello", "value": ["world"] },
+ { "op": "remove", "path": "/foo"}
+ ]
+ )"_json;
+
+ // apply the patch
+ json patched_doc = doc.patch(patch);
+
+ // output original and patched document
+ std::cout << std::setw(4) << doc << "\n\n"
+ << std::setw(4) << patched_doc << std::endl;
+}
+Output:
{
+ "baz": "qux",
+ "foo": "bar"
+}
+
+{
+ "baz": "boo",
+ "hello": [
+ "world"
+ ]
+}
+void patch_inplace(const basic_json& json_patch) const;
+JSON Patch defines a JSON document structure for expressing a sequence of operations to apply to a JSON document. With this function, a JSON Patch is applied to the current JSON value by executing all operations from the patch. This function applies a JSON patch in place and returns void.
json_patch (in)No guarantees, value may be corrupted by an unsuccessful patch operation.
parse_error.104 if the JSON patch does not consist of an array of objects.parse_error.105 if the JSON patch is malformed (e.g., mandatory attributes are missing); example: "operation add must have member path".out_of_range.401 if an array index is out of range.out_of_range.403 if a JSON pointer inside the patch could not be resolved successfully in the current JSON value; example: "key baz not found".out_of_range.405 if JSON pointer has no parent ("add", "remove", "move")out_of_range.501 if "test" operation was unsuccessful.Linear in the size of the JSON value and the length of the JSON patch. As usually only a fraction of the JSON value is affected by the patch, the complexity can usually be neglected.
Unlike patch, patch_inplace applies the operation "in place" and no copy of the JSON value is created. That makes it faster for large documents by avoiding the copy. However, the JSON value might be corrupted if the function throws an exception.
The following code shows how a JSON patch is applied to a value.
#include <iostream>
+#include <iomanip>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+using namespace nlohmann::literals;
+
+int main()
+{
+ // the original document
+ json doc = R"(
+ {
+ "baz": "qux",
+ "foo": "bar"
+ }
+ )"_json;
+
+ // the patch
+ json patch = R"(
+ [
+ { "op": "replace", "path": "/baz", "value": "boo" },
+ { "op": "add", "path": "/hello", "value": ["world"] },
+ { "op": "remove", "path": "/foo"}
+ ]
+ )"_json;
+
+ // output original document
+ std::cout << "Before\n" << std::setw(4) << doc << std::endl;
+
+ // apply the patch
+ doc.patch_inplace(patch);
+
+ // output patched document
+ std::cout << "\nAfter\n" << std::setw(4) << doc << std::endl;
+}
+Output:
Before
+{
+ "baz": "qux",
+ "foo": "bar"
+}
+
+After
+{
+ "baz": "boo",
+ "hello": [
+ "world"
+ ]
+}
+// (1)
+void push_back(basic_json&& val);
+void push_back(const basic_json& val);
+
+// (2)
+void push_back(const typename object_t::value_type& val);
+
+// (3)
+void push_back(initializer_list_t init);
+Appends the given element val to the end of the JSON array. If the function is called on a JSON null value, an empty array is created before appending val.
Inserts the given element val to the JSON object. If the function is called on a JSON null value, an empty object is created before inserting val.
This function allows using push_back with an initializer list. In case
init contains only two elements, andinit is a string,init is converted into an object element and added using push_back(const typename object_t::value_type&). Otherwise, init is converted to a JSON value and added using push_back(basic_json&&).
val (in)init (in)All functions can throw the following exception: - Throws type_error.308 when called on a type other than JSON array or null; example: "cannot use push_back() with number"
size())).init.(3) This function is required to resolve an ambiguous overload error, because pairs like {"key", "value"} can be both interpreted as object_t::value_type or std::initializer_list<basic_json>, see #235 for more information.
The example shows how push_back() and += can be used to add elements to a JSON array. Note how the null value was silently converted to a JSON array.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create JSON values
+ json array = {1, 2, 3, 4, 5};
+ json null;
+
+ // print values
+ std::cout << array << '\n';
+ std::cout << null << '\n';
+
+ // add values
+ array.push_back(6);
+ array += 7;
+ null += "first";
+ null += "second";
+
+ // print values
+ std::cout << array << '\n';
+ std::cout << null << '\n';
+}
+Output:
[1,2,3,4,5]
+null
+[1,2,3,4,5,6,7]
+["first","second"]
+The example shows how push_back() and += can be used to add elements to a JSON object. Note how the null value was silently converted to a JSON object.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create JSON values
+ json object = {{"one", 1}, {"two", 2}};
+ json null;
+
+ // print values
+ std::cout << object << '\n';
+ std::cout << null << '\n';
+
+ // add values
+ object.push_back(json::object_t::value_type("three", 3));
+ object += json::object_t::value_type("four", 4);
+ null += json::object_t::value_type("A", "a");
+ null += json::object_t::value_type("B", "b");
+
+ // print values
+ std::cout << object << '\n';
+ std::cout << null << '\n';
+}
+Output:
{"one":1,"two":2}
+null
+{"four":4,"one":1,"three":3,"two":2}
+{"A":"a","B":"b"}
+The example shows how initializer lists are treated as objects when possible.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create JSON values
+ json object = {{"one", 1}, {"two", 2}};
+ json null;
+
+ // print values
+ std::cout << object << '\n';
+ std::cout << null << '\n';
+
+ // add values:
+ object.push_back({"three", 3}); // object is extended
+ object += {"four", 4}; // object is extended
+ null.push_back({"five", 5}); // null is converted to array
+
+ // print values
+ std::cout << object << '\n';
+ std::cout << null << '\n';
+
+ // would throw:
+ //object.push_back({1, 2, 3});
+}
+Output:
{"one":1,"two":2}
+null
+{"four":4,"one":1,"three":3,"two":2}
+[["five",5]]
+reverse_iterator rbegin() noexcept;
+const_reverse_iterator rbegin() const noexcept;
+Returns an iterator to the reverse-beginning; that is, the last element.
reverse iterator to the first element
No-throw guarantee: this member function never throws exceptions.
Constant.
The following code shows an example for rbegin().
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create an array value
+ json array = {1, 2, 3, 4, 5};
+
+ // get an iterator to the reverse-beginning
+ json::reverse_iterator it = array.rbegin();
+
+ // serialize the element that the iterator points to
+ std::cout << *it << '\n';
+}
+Output:
5
+reverse_iterator rend() noexcept;
+const_reverse_iterator rend() const noexcept;
+Returns an iterator to the reverse-end; that is, one before the first element. This element acts as a placeholder, attempting to access it results in undefined behavior.
reverse iterator to the element following the last element
No-throw guarantee: this member function never throws exceptions.
Constant.
The following code shows an example for eend().
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create an array value
+ json array = {1, 2, 3, 4, 5};
+
+ // get an iterator to the reverse-end
+ json::reverse_iterator it = array.rend();
+
+ // increment the iterator to point to the first element
+ --it;
+
+ // serialize the element that the iterator points to
+ std::cout << *it << '\n';
+}
+Output:
1
+// (1)
+template <typename InputType, typename SAX>
+static bool sax_parse(InputType&& i,
+ SAX* sax,
+ input_format_t format = input_format_t::json,
+ const bool strict = true,
+ const bool ignore_comments = false);
+
+// (2)
+template<class IteratorType, class SAX>
+static bool sax_parse(IteratorType first, IteratorType last,
+ SAX* sax,
+ input_format_t format = input_format_t::json,
+ const bool strict = true,
+ const bool ignore_comments = false);
+Read from input and generate SAX events
Read from a pair of character iterators
The value_type of the iterator must be an integral type with size of 1, 2 or 4 bytes, which will be interpreted respectively as UTF-8, UTF-16 and UTF-32.
The SAX event lister must follow the interface of json_sax.
InputTypeA compatible input, for instance:
std::istream objectFILE pointerobj for which begin(obj) and end(obj) produces a valid pair of iterators.IteratorTypeSAXi (in)sax (in)format (in)input_format_t::json by default), see input_format_t for more informationstrict (in)true by default)ignore_comments (in)true) or yield a parse error (false); (optional, false by default)first (in)last (in)return value of the last processed SAX event
Linear in the length of the input. The parser is a predictive LL(1) parser. The complexity can be higher if the SAX consumer sax has a super-linear complexity.
A UTF-8 byte order mark is silently ignored.
The example below demonstrates the sax_parse() function reading from string and processing the events with a user-defined SAX event consumer.
#include <iostream>
+#include <iomanip>
+#include <sstream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+// a simple event consumer that collects string representations of the passed
+// values; note inheriting from json::json_sax_t is not required, but can
+// help not to forget a required function
+class sax_event_consumer : public json::json_sax_t
+{
+ public:
+ std::vector<std::string> events;
+
+ bool null() override
+ {
+ events.push_back("null()");
+ return true;
+ }
+
+ bool boolean(bool val) override
+ {
+ events.push_back("boolean(val=" + std::string(val ? "true" : "false") + ")");
+ return true;
+ }
+
+ bool number_integer(number_integer_t val) override
+ {
+ events.push_back("number_integer(val=" + std::to_string(val) + ")");
+ return true;
+ }
+
+ bool number_unsigned(number_unsigned_t val) override
+ {
+ events.push_back("number_unsigned(val=" + std::to_string(val) + ")");
+ return true;
+ }
+
+ bool number_float(number_float_t val, const string_t& s) override
+ {
+ events.push_back("number_float(val=" + std::to_string(val) + ", s=" + s + ")");
+ return true;
+ }
+
+ bool string(string_t& val) override
+ {
+ events.push_back("string(val=" + val + ")");
+ return true;
+ }
+
+ bool start_object(std::size_t elements) override
+ {
+ events.push_back("start_object(elements=" + std::to_string(elements) + ")");
+ return true;
+ }
+
+ bool end_object() override
+ {
+ events.push_back("end_object()");
+ return true;
+ }
+
+ bool start_array(std::size_t elements) override
+ {
+ events.push_back("start_array(elements=" + std::to_string(elements) + ")");
+ return true;
+ }
+
+ bool end_array() override
+ {
+ events.push_back("end_array()");
+ return true;
+ }
+
+ bool key(string_t& val) override
+ {
+ events.push_back("key(val=" + val + ")");
+ return true;
+ }
+
+ bool binary(json::binary_t& val) override
+ {
+ events.push_back("binary(val=[...])");
+ return true;
+ }
+
+ bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override
+ {
+ events.push_back("parse_error(position=" + std::to_string(position) + ", last_token=" + last_token + ",\n ex=" + std::string(ex.what()) + ")");
+ return false;
+ }
+};
+
+int main()
+{
+ // a JSON text
+ auto text = R"(
+ {
+ "Image": {
+ "Width": 800,
+ "Height": 600,
+ "Title": "View from 15th Floor",
+ "Thumbnail": {
+ "Url": "http://www.example.com/image/481989943",
+ "Height": 125,
+ "Width": 100
+ },
+ "Animated" : false,
+ "IDs": [116, 943, 234, -38793],
+ "DeletionDate": null,
+ "Distance": 12.723374634
+ }
+ }]
+ )";
+
+ // create a SAX event consumer object
+ sax_event_consumer sec;
+
+ // parse JSON
+ bool result = json::sax_parse(text, &sec);
+
+ // output the recorded events
+ for (auto& event : sec.events)
+ {
+ std::cout << event << "\n";
+ }
+
+ // output the result of sax_parse
+ std::cout << "\nresult: " << std::boolalpha << result << std::endl;
+}
+Output:
start_object(elements=18446744073709551615)
+key(val=Image)
+start_object(elements=18446744073709551615)
+key(val=Width)
+number_unsigned(val=800)
+key(val=Height)
+number_unsigned(val=600)
+key(val=Title)
+string(val=View from 15th Floor)
+key(val=Thumbnail)
+start_object(elements=18446744073709551615)
+key(val=Url)
+string(val=http://www.example.com/image/481989943)
+key(val=Height)
+number_unsigned(val=125)
+key(val=Width)
+number_unsigned(val=100)
+end_object()
+key(val=Animated)
+boolean(val=false)
+key(val=IDs)
+start_array(elements=18446744073709551615)
+number_unsigned(val=116)
+number_unsigned(val=943)
+number_unsigned(val=234)
+number_integer(val=-38793)
+end_array()
+key(val=DeletionDate)
+null()
+key(val=Distance)
+number_float(val=12.723375, s=12.723374634)
+end_object()
+end_object()
+parse_error(position=460, last_token=12.723374634<U+000A> }<U+000A> }],
+ ex=[json.exception.parse_error.101] parse error at line 17, column 6: syntax error while parsing value - unexpected ']'; expected end of input)
+
+result: false
+ignore_comments added in version 3.9.0.Deprecation
Overload (2) replaces calls to sax_parse with a pair of iterators as their first parameter which has been deprecated in version 3.8.0. This overload will be removed in version 4.0.0. Please replace all calls like sax_parse({ptr, ptr+len}); with sax_parse(ptr, ptr+len);.
size_type size() const noexcept;
+Returns the number of elements in a JSON value.
The return value depends on the different types and is defined as follows:
| Value type | return value |
|---|---|
| null | 0 |
| boolean | 1 |
| string | 1 |
| number | 1 |
| binary | 1 |
| object | result of function object_t::size() |
| array | result of function array_t::size() |
No-throw guarantee: this function never throws exceptions.
Constant, as long as array_t and object_t satisfy the Container concept; that is, their size() functions have constant complexity.
This function does not return the length of a string stored as JSON value -- it returns the number of elements in the JSON value which is 1 in the case of a string.
The following code calls size() on the different value types.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create JSON values
+ json j_null;
+ json j_boolean = true;
+ json j_number_integer = 17;
+ json j_number_float = 23.42;
+ json j_object = {{"one", 1}, {"two", 2}};
+ json j_object_empty(json::value_t::object);
+ json j_array = {1, 2, 4, 8, 16};
+ json j_array_empty(json::value_t::array);
+ json j_string = "Hello, world";
+
+ // call size()
+ std::cout << j_null.size() << '\n';
+ std::cout << j_boolean.size() << '\n';
+ std::cout << j_number_integer.size() << '\n';
+ std::cout << j_number_float.size() << '\n';
+ std::cout << j_object.size() << '\n';
+ std::cout << j_object_empty.size() << '\n';
+ std::cout << j_array.size() << '\n';
+ std::cout << j_array_empty.size() << '\n';
+ std::cout << j_string.size() << '\n';
+}
+Output:
0
+1
+1
+1
+2
+0
+5
+0
+1
+1 for binary types in version 3.8.0.namespace std {
+ struct hash<nlohmann::basic_json>;
+}
+Return a hash value for a JSON object. The hash function tries to rely on std::hash where possible. Furthermore, the type of the JSON value is taken into account to have different hash values for null, 0, 0U, and false, etc.
The example shows how to calculate hash values for different JSON values.
#include <iostream>
+#include <iomanip>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+using namespace nlohmann::literals;
+
+int main()
+{
+ std::cout << "hash(null) = " << std::hash<json> {}(json(nullptr)) << '\n'
+ << "hash(false) = " << std::hash<json> {}(json(false)) << '\n'
+ << "hash(0) = " << std::hash<json> {}(json(0)) << '\n'
+ << "hash(0U) = " << std::hash<json> {}(json(0U)) << '\n'
+ << "hash(\"\") = " << std::hash<json> {}(json("")) << '\n'
+ << "hash({}) = " << std::hash<json> {}(json::object()) << '\n'
+ << "hash([]) = " << std::hash<json> {}(json::array()) << '\n'
+ << "hash({\"hello\": \"world\"}) = " << std::hash<json> {}("{\"hello\": \"world\"}"_json)
+ << std::endl;
+}
+Output:
hash(null) = 2654435769
+hash(false) = 2654436030
+hash(0) = 2654436095
+hash(0U) = 2654436156
+hash("") = 6142509191626859748
+hash({}) = 2654435832
+hash([]) = 2654435899
+hash({"hello": "world"}) = 4469488738203676328
+Note the output is platform-dependent.
namespace std {
+ void swap(nlohmann::basic_json& j1, nlohmann::basic_json& j2);
+}
+Exchanges the values of two JSON objects.
j1 (in, out)j2j2 (in, out)j1void swap(nlohmann::basic_json& j1, nlohmann::basic_json& j2)
+{
+ j1.swap(j2);
+}
+The following code shows how two values are swapped with std::swap.
#include <iostream>
+#include <iomanip>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create JSON values
+ json j1 = {{"one", 1}, {"two", 2}};
+ json j2 = {1, 2, 4, 8, 16};
+
+ std::cout << "j1 = " << j1 << " | j2 = " << j2 << '\n';
+
+ // swap values
+ std::swap(j1, j2);
+
+ std::cout << "j1 = " << j1 << " | j2 = " << j2 << std::endl;
+}
+Output:
j1 = {"one":1,"two":2} | j2 = [1,2,4,8,16]
+j1 = [1,2,4,8,16] | j2 = {"one":1,"two":2}
+using string_t = StringType;
+The type used to store JSON strings.
RFC 8259 describes JSON strings as follows:
A string is a sequence of zero or more Unicode characters.
To store objects in C++, a type is defined by the template parameter described below. Unicode values are split by the JSON class into byte-sized characters during deserialization.
StringTypestd::string). Note this container is used for keys/names in objects, see object_t.With the default values for StringType (std::string), the default value for string_t is std::string.
Strings are stored in UTF-8 encoding. Therefore, functions like std::string::size() or std::string::length() return the number of bytes in the string rather than the number of characters or glyphs.
RFC 8259 states:
Software implementations are typically required to test names of object members for equality. Implementations that transform the textual representation into sequences of Unicode code units and then perform the comparison numerically, code unit by code unit, are interoperable in the sense that implementations will agree in all cases on equality or inequality of two strings. For example, implementations that compare strings with escaped characters unconverted may incorrectly find that
"a\\b"and"a\u005Cb"are not equal.
This implementation is interoperable as it does compare strings code unit by code unit.
String values are stored as pointers in a basic_json type. That is, for any access to string values, a pointer of type string_t* must be dereferenced.
The following code shows that string_t is by default, a typedef to std::string.
#include <iostream>
+#include <iomanip>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ std::cout << std::boolalpha << std::is_same<std::string, json::string_t>::value << std::endl;
+}
+Output:
true
+// (1)
+void swap(reference other) noexcept;
+
+// (2)
+void swap(reference left, reference right) noexcept;
+
+// (3)
+void swap(array_t& other);
+
+// (4)
+void swap(object_t& other);
+
+// (5)
+void swap(string_t& other);
+
+// (6)
+void swap(binary_t& other);
+
+// (7)
+void swap(typename binary_t::container_type& other);
+other. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated. left with those of right. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated. Implemented as a friend function callable via ADL.other. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated. other. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated.other. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated.other. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated.other. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated. Unlike version (6), no binary subtype is involved.other (in, out)left (in, out)right (in, out)type_error.310 if called on JSON values other than arrays; example: "cannot use swap() with boolean"type_error.310 if called on JSON values other than objects; example: "cannot use swap() with boolean"type_error.310 if called on JSON values other than strings; example: "cannot use swap() with boolean"type_error.310 if called on JSON values other than binaries; example: "cannot use swap() with boolean"type_error.310 if called on JSON values other than binaries; example: "cannot use swap() with boolean"Constant.
The example below shows how JSON values can be swapped with swap().
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create two JSON values
+ json j1 = {1, 2, 3, 4, 5};
+ json j2 = {{"pi", 3.141592653589793}, {"e", 2.718281828459045}};
+
+ // swap the values
+ j1.swap(j2);
+
+ // output the values
+ std::cout << "j1 = " << j1 << '\n';
+ std::cout << "j2 = " << j2 << '\n';
+}
+Output:
j1 = {"e":2.718281828459045,"pi":3.141592653589793}
+j2 = [1,2,3,4,5]
+The example below shows how arrays can be swapped with swap().
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create a JSON value
+ json value = {{"array", {1, 2, 3, 4}}};
+
+ // create an array_t
+ json::array_t array = {"Snap", "Crackle", "Pop"};
+
+ // swap the array stored in the JSON value
+ value["array"].swap(array);
+
+ // output the values
+ std::cout << "value = " << value << '\n';
+ std::cout << "array = " << array << '\n';
+}
+Output:
value = {"array":["Snap","Crackle","Pop"]}
+array = [1,2,3,4]
+The example below shows how objects can be swapped with swap().
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create a JSON value
+ json value = { {"translation", {{"one", "eins"}, {"two", "zwei"}}} };
+
+ // create an object_t
+ json::object_t object = {{"cow", "Kuh"}, {"dog", "Hund"}};
+
+ // swap the object stored in the JSON value
+ value["translation"].swap(object);
+
+ // output the values
+ std::cout << "value = " << value << '\n';
+ std::cout << "object = " << object << '\n';
+}
+Output:
value = {"translation":{"cow":"Kuh","dog":"Hund"}}
+object = {"one":"eins","two":"zwei"}
+The example below shows how strings can be swapped with swap().
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create a JSON value
+ json value = { "the good", "the bad", "the ugly" };
+
+ // create string_t
+ json::string_t string = "the fast";
+
+ // swap the object stored in the JSON value
+ value[1].swap(string);
+
+ // output the values
+ std::cout << "value = " << value << '\n';
+ std::cout << "string = " << string << '\n';
+}
+Output:
value = ["the good","the fast","the ugly"]
+string = the bad
+The example below shows how binary values can be swapped with swap().
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create a binary value
+ json value = json::binary({1, 2, 3});
+
+ // create a binary_t
+ json::binary_t binary = {{4, 5, 6}};
+
+ // swap the object stored in the JSON value
+ value.swap(binary);
+
+ // output the values
+ std::cout << "value = " << value << '\n';
+ std::cout << "binary = " << json(binary) << '\n';
+}
+Output:
value = {"bytes":[4,5,6],"subtype":null}
+binary = {"bytes":[1,2,3],"subtype":null}
+// (1)
+static std::vector<std::uint8_t> to_bjdata(const basic_json& j,
+ const bool use_size = false,
+ const bool use_type = false);
+
+// (2)
+static void to_bjdata(const basic_json& j, detail::output_adapter<std::uint8_t> o,
+ const bool use_size = false, const bool use_type = false);
+static void to_bjdata(const basic_json& j, detail::output_adapter<char> o,
+ const bool use_size = false, const bool use_type = false);
+Serializes a given JSON value j to a byte vector using the BJData (Binary JData) serialization format. BJData aims to be more compact than JSON itself, yet more efficient to parse.
The exact mapping and its limitations is described on a dedicated page.
j (in)o (in)use_size (in)false by default.use_type (in)use_size = true); optional, false by default.Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
Linear in the size of the JSON value j.
The example shows the serialization of a JSON value to a byte vector in BJData format.
#include <iostream>
+#include <iomanip>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+using namespace nlohmann::literals;
+
+// function to print BJData's diagnostic format
+void print_byte(uint8_t byte)
+{
+ if (32 < byte and byte < 128)
+ {
+ std::cout << (char)byte;
+ }
+ else
+ {
+ std::cout << (int)byte;
+ }
+}
+
+int main()
+{
+ // create a JSON value
+ json j = R"({"compact": true, "schema": false})"_json;
+
+ // serialize it to BJData
+ std::vector<std::uint8_t> v = json::to_bjdata(j);
+
+ // print the vector content
+ for (auto& byte : v)
+ {
+ print_byte(byte);
+ }
+ std::cout << std::endl;
+
+ // create an array of numbers
+ json array = {1, 2, 3, 4, 5, 6, 7, 8};
+
+ // serialize it to BJData using default representation
+ std::vector<std::uint8_t> v_array = json::to_bjdata(array);
+ // serialize it to BJData using size optimization
+ std::vector<std::uint8_t> v_array_size = json::to_bjdata(array, true);
+ // serialize it to BJData using type optimization
+ std::vector<std::uint8_t> v_array_size_and_type = json::to_bjdata(array, true, true);
+
+ // print the vector contents
+ for (auto& byte : v_array)
+ {
+ print_byte(byte);
+ }
+ std::cout << std::endl;
+
+ for (auto& byte : v_array_size)
+ {
+ print_byte(byte);
+ }
+ std::cout << std::endl;
+
+ for (auto& byte : v_array_size_and_type)
+ {
+ print_byte(byte);
+ }
+ std::cout << std::endl;
+}
+Output:
{i7compactTi6schemaF}
+[i1i2i3i4i5i6i7i8]
+[#i8i1i2i3i4i5i6i7i8
+[$i#i812345678
+// (1)
+static std::vector<std::uint8_t> to_bson(const basic_json& j);
+
+// (2)
+static void to_bson(const basic_json& j, detail::output_adapter<std::uint8_t> o);
+static void to_bson(const basic_json& j, detail::output_adapter<char> o);
+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 exact mapping and its limitations is described on a dedicated page.
j (in)o (in)Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
Linear in the size of the JSON value j.
The example shows the serialization of a JSON value to a byte vector in BSON format.
#include <iostream>
+#include <iomanip>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+using namespace nlohmann::literals;
+
+int main()
+{
+ // create a JSON value
+ json j = R"({"compact": true, "schema": 0})"_json;
+
+ // serialize it to BSON
+ std::vector<std::uint8_t> v = json::to_bson(j);
+
+ // print the vector content
+ for (auto& byte : v)
+ {
+ std::cout << "0x" << std::hex << std::setw(2) << std::setfill('0') << (int)byte << " ";
+ }
+ std::cout << std::endl;
+}
+Output:
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
+// (1)
+static std::vector<std::uint8_t> to_cbor(const basic_json& j);
+
+// (2)
+static void to_cbor(const basic_json& j, detail::output_adapter<std::uint8_t> o);
+static void to_cbor(const basic_json& j, detail::output_adapter<char> o);
+Serializes a given JSON value j to a byte vector using the CBOR (Concise Binary Object Representation) serialization format. CBOR is a binary serialization format which aims to be more compact than JSON itself, yet more efficient to parse.
The exact mapping and its limitations is described on a dedicated page.
j (in)o (in)Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
Linear in the size of the JSON value j.
The example shows the serialization of a JSON value to a byte vector in CBOR format.
#include <iostream>
+#include <iomanip>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+using namespace nlohmann::literals;
+
+int main()
+{
+ // create a JSON value
+ json j = R"({"compact": true, "schema": 0})"_json;
+
+ // serialize it to CBOR
+ std::vector<std::uint8_t> v = json::to_cbor(j);
+
+ // print the vector content
+ for (auto& byte : v)
+ {
+ std::cout << "0x" << std::hex << std::setw(2) << std::setfill('0') << (int)byte << " ";
+ }
+ std::cout << std::endl;
+}
+Output:
0xa2 0x67 0x63 0x6f 0x6d 0x70 0x61 0x63 0x74 0xf5 0x66 0x73 0x63 0x68 0x65 0x6d 0x61 0x00
+// (1)
+static std::vector<std::uint8_t> to_msgpack(const basic_json& j);
+
+// (2)
+static void to_msgpack(const basic_json& j, detail::output_adapter<std::uint8_t> o);
+static void to_msgpack(const basic_json& j, detail::output_adapter<char> o);
+Serializes a given JSON value j to a byte vector using the MessagePack serialization format. MessagePack is a binary serialization format which aims to be more compact than JSON itself, yet more efficient to parse.
The exact mapping and its limitations is described on a dedicated page.
j (in)o (in)Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
Linear in the size of the JSON value j.
The example shows the serialization of a JSON value to a byte vector in MessagePack format.
#include <iostream>
+#include <iomanip>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+using namespace nlohmann::literals;
+
+int main()
+{
+ // create a JSON value
+ json j = R"({"compact": true, "schema": 0})"_json;
+
+ // serialize it to MessagePack
+ std::vector<std::uint8_t> v = json::to_msgpack(j);
+
+ // print the vector content
+ for (auto& byte : v)
+ {
+ std::cout << "0x" << std::hex << std::setw(2) << std::setfill('0') << (int)byte << " ";
+ }
+ std::cout << std::endl;
+}
+Output:
0x82 0xa7 0x63 0x6f 0x6d 0x70 0x61 0x63 0x74 0xc3 0xa6 0x73 0x63 0x68 0x65 0x6d 0x61 0x00
+template <typename BasicJsonType>
+std::string to_string(const BasicJsonType& j);
+This function implements a user-defined to_string for JSON objects.
BasicJsonTypebasic_jsonstring containing the serialization of the JSON value
Strong guarantee: if an exception is thrown, there are no changes to any JSON value.
Throws type_error.316 if a string stored inside the JSON value is not UTF-8 encoded
Linear.
template <typename BasicJsonType>
+std::string to_string(const BasicJsonType& j)
+{
+ return j.dump();
+}
+The following code shows how the library's to_string() function integrates with others, allowing argument-dependent lookup.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+using std::to_string;
+
+int main()
+{
+ // create values
+ json j = {{"one", 1}, {"two", 2}};
+ int i = 42;
+
+ // use ADL to select best to_string function
+ auto j_str = to_string(j); // calling nlohmann::to_string
+ auto i_str = to_string(i); // calling std::to_string
+
+ // serialize without indentation
+ std::cout << j_str << "\n\n"
+ << i_str << std::endl;
+}
+Output:
{"one":1,"two":2}
+
+42
+Added in version 3.7.0.
// (1)
+static std::vector<std::uint8_t> to_ubjson(const basic_json& j,
+ const bool use_size = false,
+ const bool use_type = false);
+
+// (2)
+static void to_ubjson(const basic_json& j, detail::output_adapter<std::uint8_t> o,
+ const bool use_size = false, const bool use_type = false);
+static void to_ubjson(const basic_json& j, detail::output_adapter<char> o,
+ const bool use_size = false, const bool use_type = false);
+Serializes a given JSON value j to a byte vector using the UBJSON (Universal Binary JSON) serialization format. UBJSON aims to be more compact than JSON itself, yet more efficient to parse.
The exact mapping and its limitations is described on a dedicated page.
j (in)o (in)use_size (in)false by default.use_type (in)use_size = true); optional, false by default.Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
Linear in the size of the JSON value j.
The example shows the serialization of a JSON value to a byte vector in UBJSON format.
#include <iostream>
+#include <iomanip>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+using namespace nlohmann::literals;
+
+// function to print UBJSON's diagnostic format
+void print_byte(uint8_t byte)
+{
+ if (32 < byte and byte < 128)
+ {
+ std::cout << (char)byte;
+ }
+ else
+ {
+ std::cout << (int)byte;
+ }
+}
+
+int main()
+{
+ // create a JSON value
+ json j = R"({"compact": true, "schema": false})"_json;
+
+ // serialize it to UBJSON
+ std::vector<std::uint8_t> v = json::to_ubjson(j);
+
+ // print the vector content
+ for (auto& byte : v)
+ {
+ print_byte(byte);
+ }
+ std::cout << std::endl;
+
+ // create an array of numbers
+ json array = {1, 2, 3, 4, 5, 6, 7, 8};
+
+ // serialize it to UBJSON using default representation
+ std::vector<std::uint8_t> v_array = json::to_ubjson(array);
+ // serialize it to UBJSON using size optimization
+ std::vector<std::uint8_t> v_array_size = json::to_ubjson(array, true);
+ // serialize it to UBJSON using type optimization
+ std::vector<std::uint8_t> v_array_size_and_type = json::to_ubjson(array, true, true);
+
+ // print the vector contents
+ for (auto& byte : v_array)
+ {
+ print_byte(byte);
+ }
+ std::cout << std::endl;
+
+ for (auto& byte : v_array_size)
+ {
+ print_byte(byte);
+ }
+ std::cout << std::endl;
+
+ for (auto& byte : v_array_size_and_type)
+ {
+ print_byte(byte);
+ }
+ std::cout << std::endl;
+}
+Output:
{i7compactTi6schemaF}
+[i1i2i3i4i5i6i7i8]
+[#i8i1i2i3i4i5i6i7i8
+[$i#i812345678
+constexpr value_t type() const noexcept;
+Return the type of the JSON value as a value from the value_t enumeration.
the type of the JSON value
| Value type | return value |
|---|---|
null | value_t::null |
| boolean | value_t::boolean |
| string | value_t::string |
| number (integer) | value_t::number_integer |
| number (unsigned integer) | value_t::number_unsigned |
| number (floating-point) | value_t::number_float |
| object | value_t::object |
| array | value_t::array |
| binary | value_t::binary |
| discarded | value_t::discarded |
No-throw guarantee: this member function never throws exceptions.
Constant.
The following code exemplifies type() for all JSON types.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create JSON values
+ json j_null;
+ json j_boolean = true;
+ json j_number_integer = -17;
+ json j_number_unsigned = 42u;
+ json j_number_float = 23.42;
+ json j_object = {{"one", 1}, {"two", 2}};
+ json j_array = {1, 2, 4, 8, 16};
+ json j_string = "Hello, world";
+
+ // call type()
+ std::cout << std::boolalpha;
+ std::cout << (j_null.type() == json::value_t::null) << '\n';
+ std::cout << (j_boolean.type() == json::value_t::boolean) << '\n';
+ std::cout << (j_number_integer.type() == json::value_t::number_integer) << '\n';
+ std::cout << (j_number_unsigned.type() == json::value_t::number_unsigned) << '\n';
+ std::cout << (j_number_float.type() == json::value_t::number_float) << '\n';
+ std::cout << (j_object.type() == json::value_t::object) << '\n';
+ std::cout << (j_array.type() == json::value_t::array) << '\n';
+ std::cout << (j_string.type() == json::value_t::string) << '\n';
+}
+Output:
true
+true
+true
+true
+true
+true
+true
+true
+class type_error : public exception;
+This exception is thrown in case of a type error; that is, a library function is executed on a JSON value whose type does not match the expected semantics.
Exceptions have ids 3xx (see list of type errors).
The following code shows how a type_error exception can be caught.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ try
+ {
+ // calling push_back() on a string value
+ json j = "string";
+ j.push_back("another string");
+ }
+ catch (json::type_error& e)
+ {
+ // output exception information
+ std::cout << "message: " << e.what() << '\n'
+ << "exception id: " << e.id << std::endl;
+ }
+}
+Output:
message: [json.exception.type_error.308] cannot use push_back() with string
+exception id: 308
+parse_error for exceptions indicating a parse errorinvalid_iterator for exceptions indicating errors with iteratorsout_of_range for exceptions indicating access out of the defined rangeother_error for exceptions indicating other library errorsconst char* type_name() const noexcept;
+Returns the type name as string to be used in error messages -- usually to indicate that a function was called on a wrong JSON type.
a string representation of the type (value_t):
| Value type | return value |
|---|---|
null | "null" |
| boolean | "boolean" |
| string | "string" |
| number (integer, unsigned integer, floating-point) | "number" |
| object | "object" |
| array | "array" |
| binary | "binary" |
| discarded | "discarded" |
No-throw guarantee: this member function never throws exceptions.
Constant.
The following code exemplifies type_name() for all JSON types.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create JSON values
+ json j_null;
+ json j_boolean = true;
+ json j_number_integer = -17;
+ json j_number_unsigned = 42u;
+ json j_number_float = 23.42;
+ json j_object = {{"one", 1}, {"two", 2}};
+ json j_array = {1, 2, 4, 8, 16};
+ json j_string = "Hello, world";
+
+ // call type_name()
+ std::cout << j_null << " is a " << j_null.type_name() << '\n';
+ std::cout << j_boolean << " is a " << j_boolean.type_name() << '\n';
+ std::cout << j_number_integer << " is a " << j_number_integer.type_name() << '\n';
+ std::cout << j_number_unsigned << " is a " << j_number_unsigned.type_name() << '\n';
+ std::cout << j_number_float << " is a " << j_number_float.type_name() << '\n';
+ std::cout << j_object << " is an " << j_object.type_name() << '\n';
+ std::cout << j_array << " is an " << j_array.type_name() << '\n';
+ std::cout << j_string << " is a " << j_string.type_name() << '\n';
+}
+Output:
null is a null
+true is a boolean
+-17 is a number
+42 is a number
+23.42 is a number
+{"one":1,"two":2} is an object
+[1,2,4,8,16] is an array
+"Hello, world" is a string
+const char* and added noexcept in version 3.0.0.basic_json unflatten() const;
+The function restores the arbitrary nesting of a JSON value that has been flattened before using the flatten() function. The JSON value must meet certain constraints:
the original JSON from a flattened version
Strong exception safety: if an exception occurs, the original value stays intact.
The function can throw the following exceptions:
type_error.314 if value is not an objecttype_error.315 if object values are not primitiveLinear in the size the JSON value.
Empty objects and arrays are flattened by flatten() to null values and can not unflattened to their original type. Apart from this example, for a JSON value j, the following is always true: j == j.flatten().unflatten().
The following code shows how a flattened JSON object is unflattened into the original nested JSON object.
#include <iostream>
+#include <iomanip>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create JSON value
+ json j_flattened =
+ {
+ {"/answer/everything", 42},
+ {"/happy", true},
+ {"/list/0", 1},
+ {"/list/1", 0},
+ {"/list/2", 2},
+ {"/name", "Niels"},
+ {"/nothing", nullptr},
+ {"/object/currency", "USD"},
+ {"/object/value", 42.99},
+ {"/pi", 3.141}
+ };
+
+ // call unflatten()
+ std::cout << std::setw(4) << j_flattened.unflatten() << '\n';
+}
+Output:
{
+ "answer": {
+ "everything": 42
+ },
+ "happy": true,
+ "list": [
+ 1,
+ 0,
+ 2
+ ],
+ "name": "Niels",
+ "nothing": null,
+ "object": {
+ "currency": "USD",
+ "value": 42.99
+ },
+ "pi": 3.141
+}
+// (1)
+void update(const_reference j, bool merge_objects = false);
+
+// (2)
+void update(const_iterator first, const_iterator last, bool merge_objects = false);
+j.[first, last)When merge_objects is false (default), existing keys are overwritten. When merge_objects is true, recursively merges objects with common keys.
The function is motivated by Python's dict.update function.
j (in)merge_objects (in)true, existing keys are not overwritten, but contents of objects are merged recursively (default: false)first (in)last (in)type_error.312 if called on JSON values other than objects; example: "cannot use update() with string"type_error.312 if called on JSON values other than objects; example: "cannot use update() with string"invalid_iterator.202 if called on an iterator which does not belong to the current JSON value; example: "iterator does not fit current value"invalid_iterator.210 if first and last do not belong to the same JSON value; example: "iterators do not fit"The example shows how update() is used.
#include <iostream>
+#include <iomanip>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+using namespace nlohmann::literals;
+
+int main()
+{
+ // create two JSON objects
+ json o1 = R"( {"color": "red", "price": 17.99, "names": {"de": "Flugzeug"}} )"_json;
+ json o2 = R"( {"color": "blue", "speed": 100, "names": {"en": "plane"}} )"_json;
+ json o3 = o1;
+
+ // add all keys from o2 to o1 (updating "color", replacing "names")
+ o1.update(o2);
+
+ // add all keys from o2 to o1 (updating "color", merging "names")
+ o3.update(o2, true);
+
+ // output updated object o1 and o3
+ std::cout << std::setw(2) << o1 << '\n';
+ std::cout << std::setw(2) << o3 << '\n';
+}
+Output:
{
+ "color": "blue",
+ "names": {
+ "en": "plane"
+ },
+ "price": 17.99,
+ "speed": 100
+}
+{
+ "color": "blue",
+ "names": {
+ "de": "Flugzeug",
+ "en": "plane"
+ },
+ "price": 17.99,
+ "speed": 100
+}
+The example shows how update() is used.
#include <iostream>
+#include <iomanip>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+using namespace nlohmann::literals;
+
+int main()
+{
+ // create two JSON objects
+ json o1 = R"( {"color": "red", "price": 17.99, "names": {"de": "Flugzeug"}} )"_json;
+ json o2 = R"( {"color": "blue", "speed": 100, "names": {"en": "plane"}} )"_json;
+ json o3 = o1;
+
+ // add all keys from o2 to o1 (updating "color", replacing "names")
+ o1.update(o2.begin(), o2.end());
+
+ // add all keys from o2 to o1 (updating "color", merging "names")
+ o3.update(o2.begin(), o2.end(), true);
+
+ // output updated object o1 and o3
+ std::cout << std::setw(2) << o1 << '\n';
+ std::cout << std::setw(2) << o3 << '\n';
+}
+Output:
{
+ "color": "blue",
+ "names": {
+ "en": "plane"
+ },
+ "price": 17.99,
+ "speed": 100
+}
+{
+ "color": "blue",
+ "names": {
+ "de": "Flugzeug",
+ "en": "plane"
+ },
+ "price": 17.99,
+ "speed": 100
+}
+One common use case for this function is the handling of user settings. Assume your application can be configured in some aspects:
{
+ "color": "red",
+ "active": true,
+ "name": {"de": "Maus", "en": "mouse"}
+}
+The user may override the default settings selectively:
{
+ "color": "blue",
+ "name": {"es": "ratón"},
+}
+Then update manages the merging of default settings and user settings:
auto user_settings = json::parse("config.json");
+auto effective_settings = get_default_settings();
+effective_settings.update(user_settings);
+Now effective_settings contains the default settings, but those keys set by the user are overwritten:
{
+ "color": "blue",
+ "active": true,
+ "name": {"es": "ratón"}
+}
+Note existing keys were just overwritten. To merge objects, merge_objects setting should be set to true:
auto user_settings = json::parse("config.json");
+auto effective_settings = get_default_settings();
+effective_settings.update(user_settings, true);
+{
+ "color": "blue",
+ "active": true,
+ "name": {"de": "Maus", "en": "mouse", "es": "ratón"}
+}
+merge_objects parameter in 3.10.4.// (1)
+template<class ValueType>
+ValueType value(const typename object_t::key_type& key,
+ ValueType&& default_value) const;
+
+// (2)
+template<class ValueType, class KeyType>
+ValueType value(KeyType&& key,
+ ValueType&& default_value) const;
+
+// (3)
+template<class ValueType>
+ValueType value(const json_pointer& ptr,
+ const ValueType& default_value) const;
+Returns either a copy of an object's element at the specified key key or a given default value if no element with key key exists.
The function is basically equivalent to executing
try {
+ return at(key);
+} catch(out_of_range) {
+ return default_value;
+}
+See 1. This overload is only available if KeyType is comparable with typename object_t::key_type and typename object_comparator_t::is_transparent denotes a type.
Returns either a copy of an object's element at the specified JSON pointer ptr or a given default value if no value at ptr exists.
The function is basically equivalent to executing
try {
+ return at(ptr);
+} catch(out_of_range) {
+ return default_value;
+}
+Differences to at and operator[]
at, this function does not throw if the given key/ptr was not found.operator[], this function does not implicitly add an element to the position defined by key/ptr key. This function is furthermore also applicable to const objects.KeyTypejson_pointer that is comparable with string_t using object_comparator_t. This can also be a string view (C++17).ValueTypeint for JSON integer numbers, bool for JSON booleans, or std::vector types for JSON arrays. Note the type of the expected value at key/ptr and the default value default_value must be compatible.key (in)default_value (in)key/ptr found no valueptr (in)key or default_value if key is not foundkey or default_value if key is not foundptr or default_value if no value for ptr is foundStrong guarantee: if an exception is thrown, there are no changes to any JSON value.
type_error.302 if default_value does not match the type of the value at keytype_error.306 if the JSON value is not an object; in that case, using value() with a key makes no sense.type_error.302 if default_value does not match the type of the value at ptrtype_error.306 if the JSON value is not an object; in that case, using value() with a key makes no sense.The example below shows how object elements can be queried with a default value.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create a JSON object with different entry types
+ json j =
+ {
+ {"integer", 1},
+ {"floating", 42.23},
+ {"string", "hello world"},
+ {"boolean", true},
+ {"object", {{"key1", 1}, {"key2", 2}}},
+ {"array", {1, 2, 3}}
+ };
+
+ // access existing values
+ int v_integer = j.value("integer", 0);
+ double v_floating = j.value("floating", 47.11);
+
+ // access nonexisting values and rely on default value
+ std::string v_string = j.value("nonexisting", "oops");
+ bool v_boolean = j.value("nonexisting", false);
+
+ // output values
+ std::cout << std::boolalpha << v_integer << " " << v_floating
+ << " " << v_string << " " << v_boolean << "\n";
+}
+Output:
1 42.23 oops false
+The example below shows how object elements can be queried with a default value.
#include <iostream>
+#include <string_view>
+#include <nlohmann/json.hpp>
+
+using namespace std::string_view_literals;
+using json = nlohmann::json;
+
+int main()
+{
+ // create a JSON object with different entry types
+ json j =
+ {
+ {"integer", 1},
+ {"floating", 42.23},
+ {"string", "hello world"},
+ {"boolean", true},
+ {"object", {{"key1", 1}, {"key2", 2}}},
+ {"array", {1, 2, 3}}
+ };
+
+ // access existing values
+ int v_integer = j.value("integer"sv, 0);
+ double v_floating = j.value("floating"sv, 47.11);
+
+ // access nonexisting values and rely on default value
+ std::string v_string = j.value("nonexisting"sv, "oops");
+ bool v_boolean = j.value("nonexisting"sv, false);
+
+ // output values
+ std::cout << std::boolalpha << v_integer << " " << v_floating
+ << " " << v_string << " " << v_boolean << "\n";
+}
+Output:
1 42.23 oops false
+The example below shows how object elements can be queried with a default value.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+using namespace nlohmann::literals;
+
+int main()
+{
+ // create a JSON object with different entry types
+ json j =
+ {
+ {"integer", 1},
+ {"floating", 42.23},
+ {"string", "hello world"},
+ {"boolean", true},
+ {"object", {{"key1", 1}, {"key2", 2}}},
+ {"array", {1, 2, 3}}
+ };
+
+ // access existing values
+ int v_integer = j.value("/integer"_json_pointer, 0);
+ double v_floating = j.value("/floating"_json_pointer, 47.11);
+
+ // access nonexisting values and rely on default value
+ std::string v_string = j.value("/nonexisting"_json_pointer, "oops");
+ bool v_boolean = j.value("/nonexisting"_json_pointer, false);
+
+ // output values
+ std::cout << std::boolalpha << v_integer << " " << v_floating
+ << " " << v_string << " " << v_boolean << "\n";
+}
+Output:
1 42.23 oops false
+at for access by reference with range checkingoperator[] for unchecked access by referencedefault_value type from const ValueType& to ValueType&& in version 3.11.0.ValueType the first template parameter in version 3.11.2.enum class value_t : std::uint8_t {
+ null,
+ object,
+ array,
+ string,
+ boolean,
+ number_integer,
+ number_unsigned,
+ number_float,
+ binary,
+ discarded
+};
+This enumeration collects the different JSON types. It is internally used to distinguish the stored values, and the functions is_null, is_object, is_array, is_string, is_boolean, is_number (with is_number_integer, is_number_unsigned, and is_number_float), is_discarded, is_binary, is_primitive, and is_structured rely on it.
Ordering
The order of types is as follows:
nullbooleannumber_integer, number_unsigned, number_floatobjectarraystringbinarydiscarded is unordered.
Types of numbers
There are three enumerators for numbers (number_integer, number_unsigned, and number_float) to distinguish between different types of numbers:
number_unsigned_t for unsigned integersnumber_integer_t for signed integersnumber_float_t for floating-point numbers or to approximate integers which do not fit into the limits of their respective typeComparison operators
operator< and operator<=> (since C++20) are overloaded and compare according to the ordering described above. Until C++20 all other relational and equality operators yield results according to the integer value of each enumerator. Since C++20 some compilers consider the rewritten candidates generated from operator<=> during overload resolution, while others do not. For predictable and portable behavior use:
operator< or operator<=> when wanting to compare according to the order described aboveoperator== or operator!= when wanting to compare according to each enumerators integer valueThe following code how type() queries the value_t for all JSON types.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create JSON values
+ json j_null;
+ json j_boolean = true;
+ json j_number_integer = -17;
+ json j_number_unsigned = 42u;
+ json j_number_float = 23.42;
+ json j_object = {{"one", 1}, {"two", 2}};
+ json j_array = {1, 2, 4, 8, 16};
+ json j_string = "Hello, world";
+
+ // call type()
+ std::cout << std::boolalpha;
+ std::cout << (j_null.type() == json::value_t::null) << '\n';
+ std::cout << (j_boolean.type() == json::value_t::boolean) << '\n';
+ std::cout << (j_number_integer.type() == json::value_t::number_integer) << '\n';
+ std::cout << (j_number_unsigned.type() == json::value_t::number_unsigned) << '\n';
+ std::cout << (j_number_float.type() == json::value_t::number_float) << '\n';
+ std::cout << (j_object.type() == json::value_t::object) << '\n';
+ std::cout << (j_array.type() == json::value_t::array) << '\n';
+ std::cout << (j_string.type() == json::value_t::string) << '\n';
+}
+Output:
true
+true
+true
+true
+true
+true
+true
+true
+// (1)
+byte_container_with_subtype();
+
+// (2)
+byte_container_with_subtype(const container_type& container);
+byte_container_with_subtype(container_type&& container);
+
+// (3)
+byte_container_with_subtype(const container_type& container, subtype_type subtype);
+byte_container_with_subtype(container_type&& container, subtype_type subtype);
+container (in)subtype (in)The example below demonstrates how byte containers can be created.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+// define a byte container based on std::vector
+using byte_container_with_subtype = nlohmann::byte_container_with_subtype<std::vector<std::uint8_t>>;
+
+using json = nlohmann::json;
+
+int main()
+{
+ // (1) create empty container
+ auto c1 = byte_container_with_subtype();
+
+ std::vector<std::uint8_t> bytes = {{0xca, 0xfe, 0xba, 0xbe}};
+
+ // (2) create container
+ auto c2 = byte_container_with_subtype(bytes);
+
+ // (3) create container with subtype
+ auto c3 = byte_container_with_subtype(bytes, 42);
+
+ std::cout << json(c1) << "\n" << json(c2) << "\n" << json(c3) << std::endl;
+}
+Output:
{"bytes":[],"subtype":null}
+{"bytes":[202,254,186,190],"subtype":null}
+{"bytes":[202,254,186,190],"subtype":42}
+Since version 3.8.0.
void clear_subtype() noexcept;
+Clears the binary subtype and flags the value as not having a subtype, which has implications for serialization; for instance MessagePack will prefer the bin family over the ext family.
No-throw guarantee: this function never throws exceptions.
Constant.
The example below demonstrates how clear_subtype can remove subtypes.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+// define a byte container based on std::vector
+using byte_container_with_subtype = nlohmann::byte_container_with_subtype<std::vector<std::uint8_t>>;
+
+using json = nlohmann::json;
+
+int main()
+{
+ std::vector<std::uint8_t> bytes = {{0xca, 0xfe, 0xba, 0xbe}};
+
+ // create container with subtype
+ auto c1 = byte_container_with_subtype(bytes, 42);
+
+ std::cout << "before calling clear_subtype(): " << json(c1) << '\n';
+
+ c1.clear_subtype();
+
+ std::cout << "after calling clear_subtype(): " << json(c1) << '\n';
+}
+Output:
before calling clear_subtype(): {"bytes":[202,254,186,190],"subtype":42}
+after calling clear_subtype(): {"bytes":[202,254,186,190],"subtype":null}
+Since version 3.8.0.
constexpr bool has_subtype() const noexcept;
+Returns whether the value has a subtype.
whether the value has a subtype
No-throw guarantee: this function never throws exceptions.
Constant.
The example below demonstrates how has_subtype can check whether a subtype was set.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+// define a byte container based on std::vector
+using byte_container_with_subtype = nlohmann::byte_container_with_subtype<std::vector<std::uint8_t>>;
+
+int main()
+{
+ std::vector<std::uint8_t> bytes = {{0xca, 0xfe, 0xba, 0xbe}};
+
+ // create container
+ auto c1 = byte_container_with_subtype(bytes);
+
+ // create container with subtype
+ auto c2 = byte_container_with_subtype(bytes, 42);
+
+ std::cout << std::boolalpha << "c1.has_subtype() = " << c1.has_subtype()
+ << "\nc2.has_subtype() = " << c2.has_subtype() << std::endl;
+}
+Output:
c1.has_subtype() = false
+c2.has_subtype() = true
+Since version 3.8.0.
template<typename BinaryType>
+class byte_container_with_subtype : public BinaryType;
+This type extends the template parameter BinaryType provided to basic_json with a subtype used by BSON and MessagePack. This type exists so that the user does not have to specify a type themselves with a specific naming scheme in order to override the binary type.
BinaryTypestd::vector<std::uint8_t> by default)BinaryType)std::uint64_t)std::uint64_t in 3.10.0.void set_subtype(subtype_type subtype) noexcept;
+Sets the binary subtype of the value, also flags a binary JSON value as having a subtype, which has implications for serialization.
subtype (in)No-throw guarantee: this function never throws exceptions.
Constant.
The example below demonstrates how a subtype can be set with set_subtype.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+// define a byte container based on std::vector
+using byte_container_with_subtype = nlohmann::byte_container_with_subtype<std::vector<std::uint8_t>>;
+
+using json = nlohmann::json;
+
+int main()
+{
+ std::vector<std::uint8_t> bytes = {{0xca, 0xfe, 0xba, 0xbe}};
+
+ // create container without subtype
+ auto c = byte_container_with_subtype(bytes);
+
+ std::cout << "before calling set_subtype(42): " << json(c) << '\n';
+
+ // set the subtype
+ c.set_subtype(42);
+
+ std::cout << "after calling set_subtype(42): " << json(c) << '\n';
+}
+Output:
before calling set_subtype(42): {"bytes":[202,254,186,190],"subtype":null}
+after calling set_subtype(42): {"bytes":[202,254,186,190],"subtype":42}
+Since version 3.8.0.
constexpr subtype_type subtype() const noexcept;
+Returns the numerical subtype of the value if it has a subtype. If it does not have a subtype, this function will return subtype_type(-1) as a sentinel value.
the numerical subtype of the binary value, or subtype_type(-1) if no subtype is set
No-throw guarantee: this function never throws exceptions.
Constant.
The example below demonstrates how the subtype can be retrieved with subtype. Note how subtype_type(-1) is returned for container c1.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+// define a byte container based on std::vector
+using byte_container_with_subtype = nlohmann::byte_container_with_subtype<std::vector<std::uint8_t>>;
+
+int main()
+{
+ std::vector<std::uint8_t> bytes = {{0xca, 0xfe, 0xba, 0xbe}};
+
+ // create container
+ auto c1 = byte_container_with_subtype(bytes);
+
+ // create container with subtype
+ auto c2 = byte_container_with_subtype(bytes, 42);
+
+ std::cout << "c1.subtype() = " << c1.subtype()
+ << "\nc2.subtype() = " << c2.subtype() << std::endl;
+
+ // in case no subtype is set, return special value
+ assert(c1.subtype() == static_cast<byte_container_with_subtype::subtype_type>(-1));
+}
+Output:
c1.subtype() = 18446744073709551615
+c2.subtype() = 42
+subtype_type(-1) as documented in version 3.10.0.using json = basic_json<>;
+This type is the default specialization of the basic_json class which uses the standard template types.
The example below demonstrates how to use the type nlohmann::json.
#include <iostream>
+#include <iomanip>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create a JSON object
+ json j =
+ {
+ {"pi", 3.141},
+ {"happy", true},
+ {"name", "Niels"},
+ {"nothing", nullptr},
+ {
+ "answer", {
+ {"everything", 42}
+ }
+ },
+ {"list", {1, 0, 2}},
+ {
+ "object", {
+ {"currency", "USD"},
+ {"value", 42.99}
+ }
+ }
+ };
+
+ // add new values
+ j["new"]["key"]["value"] = {"another", "list"};
+
+ // count elements
+ auto s = j.size();
+ j["size"] = s;
+
+ // pretty print with indent of 4 spaces
+ std::cout << std::setw(4) << j << '\n';
+}
+Output:
{
+ "answer": {
+ "everything": 42
+ },
+ "happy": true,
+ "list": [
+ 1,
+ 0,
+ 2
+ ],
+ "name": "Niels",
+ "new": {
+ "key": {
+ "value": [
+ "another",
+ "list"
+ ]
+ }
+ },
+ "nothing": null,
+ "object": {
+ "currency": "USD",
+ "value": 42.99
+ },
+ "pi": 3.141,
+ "size": 8
+}
+Since version 1.0.0.
const string_t& back() const;
+Return last reference token.
Last reference token.
Throws out_of_range.405 if JSON pointer has no parent.
Constant.
The example shows the usage of back.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // different JSON Pointers
+ json::json_pointer ptr1("/foo");
+ json::json_pointer ptr2("/foo/0");
+
+ // call empty()
+ std::cout << "last reference token of \"" << ptr1 << "\" is \"" << ptr1.back() << "\"\n"
+ << "last reference token of \"" << ptr2 << "\" is \"" << ptr2.back() << "\"" << std::endl;
+}
+Output:
last reference token of "/foo" is "foo"
+last reference token of "/foo/0" is "0"
+string_t in version 3.11.0.bool empty() const noexcept;
+Return whether pointer points to the root document.
true iff the JSON pointer points to the root document.
No-throw guarantee: this function never throws exceptions.
Constant.
The example shows the result of empty for different JSON Pointers.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // different JSON Pointers
+ json::json_pointer ptr0;
+ json::json_pointer ptr1("");
+ json::json_pointer ptr2("/foo");
+ json::json_pointer ptr3("/foo/0");
+
+ // call empty()
+ std::cout << std::boolalpha
+ << "\"" << ptr0 << "\": " << ptr0.empty() << '\n'
+ << "\"" << ptr1 << "\": " << ptr1.empty() << '\n'
+ << "\"" << ptr2 << "\": " << ptr2.empty() << '\n'
+ << "\"" << ptr3 << "\": " << ptr3.empty() << std::endl;
+}
+Output:
"": true
+"": true
+"/foo": false
+"/foo/0": false
+Added in version 3.6.0.
template<typename RefStringType>
+class json_pointer;
+A JSON pointer defines a string syntax for identifying a specific value within a JSON document. It can be used with functions at and operator[]. Furthermore, JSON pointers are the base for JSON patches.
RefStringTypeDeprecation
For backwards compatibility RefStringType may also be a specialization of basic_json in which case string_t will be deduced as basic_json::string_t. This feature is deprecated and may be removed in a future major version.
basic_json to string type in version 3.11.0.explicit json_pointer(const string_t& s = "");
+Create a JSON pointer according to the syntax described in Section 3 of RFC6901.
s (in)s is nonempty and does not begin with a slash (/); see example below.~) in the given JSON pointer s is not followed by 0 (representing ~) or 1 (representing /); see example below.The example shows the construction several valid JSON pointers as well as the exceptional behavior.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // correct JSON pointers
+ json::json_pointer p1;
+ json::json_pointer p2("");
+ json::json_pointer p3("/");
+ json::json_pointer p4("//");
+ json::json_pointer p5("/foo/bar");
+ json::json_pointer p6("/foo/bar/-");
+ json::json_pointer p7("/foo/~0");
+ json::json_pointer p8("/foo/~1");
+
+ // error: JSON pointer does not begin with a slash
+ try
+ {
+ json::json_pointer p9("foo");
+ }
+ catch (json::parse_error& e)
+ {
+ std::cout << e.what() << '\n';
+ }
+
+ // error: JSON pointer uses escape symbol ~ not followed by 0 or 1
+ try
+ {
+ json::json_pointer p10("/foo/~");
+ }
+ catch (json::parse_error& e)
+ {
+ std::cout << e.what() << '\n';
+ }
+
+ // error: JSON pointer uses escape symbol ~ not followed by 0 or 1
+ try
+ {
+ json::json_pointer p11("/foo/~3");
+ }
+ catch (json::parse_error& e)
+ {
+ std::cout << e.what() << '\n';
+ }
+}
+Output:
[json.exception.parse_error.107] parse error at byte 1: JSON pointer must be empty or begin with '/' - was: 'foo'
+[json.exception.parse_error.108] parse error: escape character '~' must be followed with '0' or '1'
+[json.exception.parse_error.108] parse error: escape character '~' must be followed with '0' or '1'
+s to string_t in version 3.11.0.// until C++20
+template<typename RefStringTypeLhs, typename RefStringTypeRhs>
+bool operator==(
+ const json_pointer<RefStringTypeLhs>& lhs,
+ const json_pointer<RefStringTypeRhs>& rhs) noexcept; // (1)
+
+template<typename RefStringTypeLhs, typename StringType>
+bool operator==(
+ const json_pointer<RefStringTypeLhs>& lhs,
+ const StringType& rhs); // (2)
+
+template<typename RefStringTypeRhs, typename StringType>
+bool operator==(
+ const StringType& lhs,
+ const json_pointer<RefStringTypeRhs>& rhs); // (2)
+
+// since C++20
+class json_pointer {
+ template<typename RefStringTypeRhs>
+ bool operator==(
+ const json_pointer<RefStringTypeRhs>& rhs) const noexcept; // (1)
+
+ bool operator==(const string_t& rhs) const; // (2)
+};
+Compares two JSON pointers for equality by comparing their reference tokens.
Compares a JSON pointer and a string or a string and a JSON pointer for equality by converting the string to a JSON pointer and comparing the JSON pointers according to 1.
RefStringTypeLhs, RefStringTypeRhsStringTypejson_pointer operand (json_pointer::string_t)lhs (in)rhs (in)whether the values lhs/*this and rhs are equal
s is nonempty and does not begin with a slash (/); see example below.~) in the given JSON pointer s is not followed by 0 (representing ~) or 1 (representing /); see example below.Constant if lhs and rhs differ in the number of reference tokens, otherwise linear in the number of reference tokens.
Deprecation
Overload 2 is deprecated and will be removed in a future major version release.
The example demonstrates comparing JSON pointers.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // different JSON pointers
+ json::json_pointer ptr0;
+ json::json_pointer ptr1("");
+ json::json_pointer ptr2("/foo");
+
+ // compare JSON pointers
+ std::cout << std::boolalpha
+ << "\"" << ptr0 << "\" == \"" << ptr0 << "\": " << (ptr0 == ptr0) << '\n'
+ << "\"" << ptr0 << "\" == \"" << ptr1 << "\": " << (ptr0 == ptr1) << '\n'
+ << "\"" << ptr1 << "\" == \"" << ptr2 << "\": " << (ptr1 == ptr2) << '\n'
+ << "\"" << ptr2 << "\" == \"" << ptr2 << "\": " << (ptr2 == ptr2) << std::endl;
+}
+Output:
"" == "": true
+"" == "": true
+"" == "/foo": false
+"/foo" == "/foo": true
+The example demonstrates comparing JSON pointers and strings, and when doing so may raise an exception.
#include <exception>
+#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // different JSON pointers
+ json::json_pointer ptr0;
+ json::json_pointer ptr1("");
+ json::json_pointer ptr2("/foo");
+
+ // different strings
+ std::string str0("");
+ std::string str1("/foo");
+ std::string str2("bar");
+
+ // compare JSON pointers and strings
+ std::cout << std::boolalpha
+ << "\"" << ptr0 << "\" == \"" << str0 << "\": " << (ptr0 == str0) << '\n'
+ << "\"" << str0 << "\" == \"" << ptr1 << "\": " << (str0 == ptr1) << '\n'
+ << "\"" << ptr2 << "\" == \"" << str1 << "\": " << (ptr2 == str1) << std::endl;
+
+ try
+ {
+ std::cout << "\"" << str2 << "\" == \"" << ptr2 << "\": " << (str2 == ptr2) << std::endl;
+ }
+ catch (const json::parse_error& ex)
+ {
+ std::cout << ex.what() << std::endl;
+ }
+}
+Output:
"" == "": true
+"" == "": true
+"/foo" == "/foo": true
+"bar" == "/foo": [json.exception.parse_error.107] parse error at byte 1: JSON pointer must be empty or begin with '/' - was: 'bar'
+// until C++20
+template<typename RefStringTypeLhs, typename RefStringTypeRhs>
+bool operator!=(
+ const json_pointer<RefStringTypeLhs>& lhs,
+ const json_pointer<RefStringTypeRhs>& rhs) noexcept; // (1)
+
+template<typename RefStringTypeLhs, typename StringType>
+bool operator!=(
+ const json_pointer<RefStringTypeLhs>& lhs,
+ const StringType& rhs); // (2)
+
+template<typename RefStringTypeRhs, typename StringType>
+bool operator!=(
+ const StringType& lhs,
+ const json_pointer<RefStringTypeRhs>& rhs); // (2)
+Compares two JSON pointers for inequality by comparing their reference tokens.
Compares a JSON pointer and a string or a string and a JSON pointer for inequality by converting the string to a JSON pointer and comparing the JSON pointers according to 1.
RefStringTypeLhs, RefStringTypeRhsStringTypejson_pointer operand (json_pointer::string_t)lhs (in)rhs (in)whether the values lhs/*this and rhs are not equal
s is nonempty and does not begin with a slash (/); see example below.~) in the given JSON pointer s is not followed by 0 (representing ~) or 1 (representing /); see example below.Constant if lhs and rhs differ in the number of reference tokens, otherwise linear in the number of reference tokens.
Operator overload resolution
Since C++20 overload resolution will consider the rewritten candidate generated from operator==.
Deprecation
Overload 2 is deprecated and will be removed in a future major version release.
The example demonstrates comparing JSON pointers.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // different JSON pointers
+ json::json_pointer ptr0;
+ json::json_pointer ptr1("");
+ json::json_pointer ptr2("/foo");
+
+ // compare JSON pointers
+ std::cout << std::boolalpha
+ << "\"" << ptr0 << "\" != \"" << ptr0 << "\": " << (ptr0 != ptr0) << '\n'
+ << "\"" << ptr0 << "\" != \"" << ptr1 << "\": " << (ptr0 != ptr1) << '\n'
+ << "\"" << ptr1 << "\" != \"" << ptr2 << "\": " << (ptr1 != ptr2) << '\n'
+ << "\"" << ptr2 << "\" != \"" << ptr2 << "\": " << (ptr2 != ptr2) << std::endl;
+}
+Output:
"" != "": false
+"" != "": false
+"" != "/foo": true
+"/foo" != "/foo": false
+The example demonstrates comparing JSON pointers and strings, and when doing so may raise an exception.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // different JSON pointers
+ json::json_pointer ptr0;
+ json::json_pointer ptr1("");
+ json::json_pointer ptr2("/foo");
+
+ // different strings
+ std::string str0("");
+ std::string str1("/foo");
+ std::string str2("bar");
+
+ // compare JSON pointers and strings
+ std::cout << std::boolalpha
+ << "\"" << ptr0 << "\" != \"" << str0 << "\": " << (ptr0 != str0) << '\n'
+ << "\"" << str0 << "\" != \"" << ptr1 << "\": " << (str0 != ptr1) << '\n'
+ << "\"" << ptr2 << "\" != \"" << str1 << "\": " << (ptr2 != str1) << std::endl;
+
+ try
+ {
+ std::cout << "\"" << str2 << "\" != \"" << ptr2 << "\": " << (str2 != ptr2) << std::endl;
+ }
+ catch (const json::parse_error& ex)
+ {
+ std::cout << ex.what() << std::endl;
+ }
+}
+Output:
"" != "": false
+"" != "": false
+"/foo" != "/foo": false
+"bar" != "/foo": [json.exception.parse_error.107] parse error at byte 1: JSON pointer must be empty or begin with '/' - was: 'bar'
+// (1)
+json_pointer operator/(const json_pointer& lhs, const json_pointer& rhs);
+
+// (2)
+json_pointer operator/(const json_pointer& lhs, string_t token);
+
+// (3)
+json_pointer operator/(const json_pointer& lhs, std::size_t array_idx);
+lhs (in)rhs (in)token (in)array_idx (in)rhs appended to lhstoken appended to lhsarray_idx appended to lhslhs and rhs.lhs.lhs.The example shows the usage of operator/.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create a JSON pointer
+ json::json_pointer ptr("/foo");
+
+ // append a JSON Pointer
+ std::cout << "\"" << ptr / json::json_pointer("/bar/baz") << "\"\n";
+
+ // append a string
+ std::cout << "\"" << ptr / "fob" << "\"\n";
+
+ // append an array index
+ std::cout << "\"" << ptr / 42 << "\"" << std::endl;
+}
+Output:
"/foo/bar/baz"
+"/foo/fob"
+"/foo/42"
+token to string_t in version 3.11.0.// (1)
+json_pointer& operator/=(const json_pointer& ptr);
+
+// (2)
+json_pointer& operator/=(string_t token);
+
+// (3)
+json_pointer& operator/=(std::size_t array_idx)
+ptr (in)token (in)array_idx (in)ptr appendedtoken appended without escaping tokenarray_idx appendedptr.The example shows the usage of operator/=.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create a JSON pointer
+ json::json_pointer ptr("/foo");
+ std::cout << "\"" << ptr << "\"\n";
+
+ // append a JSON Pointer
+ ptr /= json::json_pointer("/bar/baz");
+ std::cout << "\"" << ptr << "\"\n";
+
+ // append a string
+ ptr /= "fob";
+ std::cout << "\"" << ptr << "\"\n";
+
+ // append an array index
+ ptr /= 42;
+ std::cout << "\"" << ptr << "\"" << std::endl;
+}
+Output:
"/foo"
+"/foo/bar/baz"
+"/foo/bar/baz/fob"
+"/foo/bar/baz/fob/42"
+token to string_t in version 3.11.0.operator string_t() const
+Return a string representation of the JSON pointer.
A string representation of the JSON pointer
operator string_t() const
+{
+ return to_string();
+}
+Deprecation
This function is deprecated in favor of to_string and will be removed in a future major version release.
The example shows how JSON Pointers can be implicitly converted to strings.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // different JSON Pointers
+ json::json_pointer ptr1("/foo/0");
+ json::json_pointer ptr2("/a~1b");
+
+ // implicit conversion to string
+ std::string s;
+ s += ptr1;
+ s += "\n";
+ s += ptr2;
+
+ std::cout << s << std::endl;
+}
+Output:
/foo/0
+/a~1b
+string_t and deprecated in version 3.11.0.json_pointer parent_pointer() const;
+Returns the parent of this JSON pointer.
Parent of this JSON pointer; in case this JSON pointer is the root, the root itself is returned.
Linear in the length of the JSON pointer.
The example shows the result of parent_pointer for different JSON Pointers.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // different JSON Pointers
+ json::json_pointer ptr1("");
+ json::json_pointer ptr2("/foo");
+ json::json_pointer ptr3("/foo/0");
+
+ // call parent_pointer()
+ std::cout << std::boolalpha
+ << "parent of \"" << ptr1 << "\" is \"" << ptr1.parent_pointer() << "\"\n"
+ << "parent of \"" << ptr2 << "\" is \"" << ptr2.parent_pointer() << "\"\n"
+ << "parent of \"" << ptr3 << "\" is \"" << ptr3.parent_pointer() << "\"" << std::endl;
+}
+Output:
parent of "" is ""
+parent of "/foo" is ""
+parent of "/foo/0" is "/foo"
+Added in version 3.6.0.
void pop_back();
+Remove last reference token.
Throws out_of_range.405 if JSON pointer has no parent.
Constant.
The example shows the usage of pop_back.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create empty JSON Pointer
+ json::json_pointer ptr("/foo/bar/baz");
+ std::cout << "\"" << ptr << "\"\n";
+
+ // call pop_back()
+ ptr.pop_back();
+ std::cout << "\"" << ptr << "\"\n";
+
+ ptr.pop_back();
+ std::cout << "\"" << ptr << "\"\n";
+
+ ptr.pop_back();
+ std::cout << "\"" << ptr << "\"\n";
+}
+Output:
"/foo/bar/baz"
+"/foo/bar"
+"/foo"
+""
+Added in version 3.6.0.
void push_back(const string_t& token);
+
+void push_back(string_t&& token);
+Append an unescaped token at the end of the reference pointer.
token (in)Amortized constant.
The example shows the result of push_back for different JSON Pointers.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create empty JSON Pointer
+ json::json_pointer ptr;
+ std::cout << "\"" << ptr << "\"\n";
+
+ // call push_back()
+ ptr.push_back("foo");
+ std::cout << "\"" << ptr << "\"\n";
+
+ ptr.push_back("0");
+ std::cout << "\"" << ptr << "\"\n";
+
+ ptr.push_back("bar");
+ std::cout << "\"" << ptr << "\"\n";
+}
+Output:
""
+"/foo"
+"/foo/0"
+"/foo/0/bar"
+token to string_t in version 3.11.0.using string_t = RefStringType;
+The string type used for the reference tokens making up the JSON pointer.
See basic_json::string_t for more information.
The example shows the type string_t and its relation to basic_json::string_t.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ json::json_pointer::string_t s = "This is a string.";
+
+ std::cout << s << std::endl;
+
+ std::cout << std::boolalpha << std::is_same<json::json_pointer::string_t, json::string_t>::value << std::endl;
+}
+Output:
This is a string.
+true
+string_t to_string() const;
+Return a string representation of the JSON pointer.
A string representation of the JSON pointer
For each JSON pointer ptr, it holds:
ptr == json_pointer(ptr.to_string());
+The example shows the result of to_string.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // different JSON Pointers
+ json::json_pointer ptr1("");
+ json::json_pointer ptr2("/foo");
+ json::json_pointer ptr3("/foo/0");
+ json::json_pointer ptr4("/");
+ json::json_pointer ptr5("/a~1b");
+ json::json_pointer ptr6("/c%d");
+ json::json_pointer ptr7("/e^f");
+ json::json_pointer ptr8("/g|h");
+ json::json_pointer ptr9("/i\\j");
+ json::json_pointer ptr10("/k\"l");
+ json::json_pointer ptr11("/ ");
+ json::json_pointer ptr12("/m~0n");
+
+ std::cout << "\"" << ptr1.to_string() << "\"\n"
+ << "\"" << ptr2.to_string() << "\"\n"
+ << "\"" << ptr3.to_string() << "\"\n"
+ << "\"" << ptr4.to_string() << "\"\n"
+ << "\"" << ptr5.to_string() << "\"\n"
+ << "\"" << ptr6.to_string() << "\"\n"
+ << "\"" << ptr7.to_string() << "\"\n"
+ << "\"" << ptr8.to_string() << "\"\n"
+ << "\"" << ptr9.to_string() << "\"\n"
+ << "\"" << ptr10.to_string() << "\"\n"
+ << "\"" << ptr11.to_string() << "\"\n"
+ << "\"" << ptr12.to_string() << "\"" << std::endl;
+}
+Output:
""
+"/foo"
+"/foo/0"
+"/"
+"/a~1b"
+"/c%d"
+"/e^f"
+"/g|h"
+"/i\j"
+"/k"l"
+"/ "
+"/m~0n"
+string_t in version 3.11.0.virtual bool binary(binary_t& val) = 0;
+A binary value was read.
val (in)Whether parsing should proceed.
It is safe to move the passed binary value.
The example below shows how the SAX interface is used.
#include <iostream>
+#include <iomanip>
+#include <sstream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+// a simple event consumer that collects string representations of the passed
+// values; note inheriting from json::json_sax_t is not required, but can
+// help not to forget a required function
+class sax_event_consumer : public json::json_sax_t
+{
+ public:
+ std::vector<std::string> events;
+
+ bool null() override
+ {
+ events.push_back("null()");
+ return true;
+ }
+
+ bool boolean(bool val) override
+ {
+ events.push_back("boolean(val=" + std::string(val ? "true" : "false") + ")");
+ return true;
+ }
+
+ bool number_integer(number_integer_t val) override
+ {
+ events.push_back("number_integer(val=" + std::to_string(val) + ")");
+ return true;
+ }
+
+ bool number_unsigned(number_unsigned_t val) override
+ {
+ events.push_back("number_unsigned(val=" + std::to_string(val) + ")");
+ return true;
+ }
+
+ bool number_float(number_float_t val, const string_t& s) override
+ {
+ events.push_back("number_float(val=" + std::to_string(val) + ", s=" + s + ")");
+ return true;
+ }
+
+ bool string(string_t& val) override
+ {
+ events.push_back("string(val=" + val + ")");
+ return true;
+ }
+
+ bool start_object(std::size_t elements) override
+ {
+ events.push_back("start_object(elements=" + std::to_string(elements) + ")");
+ return true;
+ }
+
+ bool end_object() override
+ {
+ events.push_back("end_object()");
+ return true;
+ }
+
+ bool start_array(std::size_t elements) override
+ {
+ events.push_back("start_array(elements=" + std::to_string(elements) + ")");
+ return true;
+ }
+
+ bool end_array() override
+ {
+ events.push_back("end_array()");
+ return true;
+ }
+
+ bool key(string_t& val) override
+ {
+ events.push_back("key(val=" + val + ")");
+ return true;
+ }
+
+ bool binary(json::binary_t& val) override
+ {
+ events.push_back("binary(val=[...])");
+ return true;
+ }
+
+ bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override
+ {
+ events.push_back("parse_error(position=" + std::to_string(position) + ", last_token=" + last_token + ",\n ex=" + std::string(ex.what()) + ")");
+ return false;
+ }
+};
+
+int main()
+{
+ // CBOR byte string
+ std::vector<std::uint8_t> vec = {{0x44, 0xcA, 0xfe, 0xba, 0xbe}};
+
+ // create a SAX event consumer object
+ sax_event_consumer sec;
+
+ // parse CBOR
+ bool result = json::sax_parse(vec, &sec, json::input_format_t::cbor);
+
+ // output the recorded events
+ for (auto& event : sec.events)
+ {
+ std::cout << event << "\n";
+ }
+
+ // output the result of sax_parse
+ std::cout << "\nresult: " << std::boolalpha << result << std::endl;
+}
+Output:
binary(val=[...])
+
+result: true
+virtual bool boolean(bool val) = 0;
+A boolean value was read.
val (in)Whether parsing should proceed.
The example below shows how the SAX interface is used.
#include <iostream>
+#include <iomanip>
+#include <sstream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+// a simple event consumer that collects string representations of the passed
+// values; note inheriting from json::json_sax_t is not required, but can
+// help not to forget a required function
+class sax_event_consumer : public json::json_sax_t
+{
+ public:
+ std::vector<std::string> events;
+
+ bool null() override
+ {
+ events.push_back("null()");
+ return true;
+ }
+
+ bool boolean(bool val) override
+ {
+ events.push_back("boolean(val=" + std::string(val ? "true" : "false") + ")");
+ return true;
+ }
+
+ bool number_integer(number_integer_t val) override
+ {
+ events.push_back("number_integer(val=" + std::to_string(val) + ")");
+ return true;
+ }
+
+ bool number_unsigned(number_unsigned_t val) override
+ {
+ events.push_back("number_unsigned(val=" + std::to_string(val) + ")");
+ return true;
+ }
+
+ bool number_float(number_float_t val, const string_t& s) override
+ {
+ events.push_back("number_float(val=" + std::to_string(val) + ", s=" + s + ")");
+ return true;
+ }
+
+ bool string(string_t& val) override
+ {
+ events.push_back("string(val=" + val + ")");
+ return true;
+ }
+
+ bool start_object(std::size_t elements) override
+ {
+ events.push_back("start_object(elements=" + std::to_string(elements) + ")");
+ return true;
+ }
+
+ bool end_object() override
+ {
+ events.push_back("end_object()");
+ return true;
+ }
+
+ bool start_array(std::size_t elements) override
+ {
+ events.push_back("start_array(elements=" + std::to_string(elements) + ")");
+ return true;
+ }
+
+ bool end_array() override
+ {
+ events.push_back("end_array()");
+ return true;
+ }
+
+ bool key(string_t& val) override
+ {
+ events.push_back("key(val=" + val + ")");
+ return true;
+ }
+
+ bool binary(json::binary_t& val) override
+ {
+ events.push_back("binary(val=[...])");
+ return true;
+ }
+
+ bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override
+ {
+ events.push_back("parse_error(position=" + std::to_string(position) + ", last_token=" + last_token + ",\n ex=" + std::string(ex.what()) + ")");
+ return false;
+ }
+};
+
+int main()
+{
+ // a JSON text
+ auto text = R"(
+ {
+ "Image": {
+ "Width": 800,
+ "Height": 600,
+ "Title": "View from 15th Floor",
+ "Thumbnail": {
+ "Url": "http://www.example.com/image/481989943",
+ "Height": 125,
+ "Width": 100
+ },
+ "Animated" : false,
+ "IDs": [116, 943, 234, -38793],
+ "DeletionDate": null,
+ "Distance": 12.723374634
+ }
+ }]
+ )";
+
+ // create a SAX event consumer object
+ sax_event_consumer sec;
+
+ // parse JSON
+ bool result = json::sax_parse(text, &sec);
+
+ // output the recorded events
+ for (auto& event : sec.events)
+ {
+ std::cout << event << "\n";
+ }
+
+ // output the result of sax_parse
+ std::cout << "\nresult: " << std::boolalpha << result << std::endl;
+}
+Output:
start_object(elements=18446744073709551615)
+key(val=Image)
+start_object(elements=18446744073709551615)
+key(val=Width)
+number_unsigned(val=800)
+key(val=Height)
+number_unsigned(val=600)
+key(val=Title)
+string(val=View from 15th Floor)
+key(val=Thumbnail)
+start_object(elements=18446744073709551615)
+key(val=Url)
+string(val=http://www.example.com/image/481989943)
+key(val=Height)
+number_unsigned(val=125)
+key(val=Width)
+number_unsigned(val=100)
+end_object()
+key(val=Animated)
+boolean(val=false)
+key(val=IDs)
+start_array(elements=18446744073709551615)
+number_unsigned(val=116)
+number_unsigned(val=943)
+number_unsigned(val=234)
+number_integer(val=-38793)
+end_array()
+key(val=DeletionDate)
+null()
+key(val=Distance)
+number_float(val=12.723375, s=12.723374634)
+end_object()
+end_object()
+parse_error(position=460, last_token=12.723374634<U+000A> }<U+000A> }],
+ ex=[json.exception.parse_error.101] parse error at line 17, column 6: syntax error while parsing value - unexpected ']'; expected end of input)
+
+result: false
+virtual bool end_array() = 0;
+The end of an array was read.
Whether parsing should proceed.
The example below shows how the SAX interface is used.
#include <iostream>
+#include <iomanip>
+#include <sstream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+// a simple event consumer that collects string representations of the passed
+// values; note inheriting from json::json_sax_t is not required, but can
+// help not to forget a required function
+class sax_event_consumer : public json::json_sax_t
+{
+ public:
+ std::vector<std::string> events;
+
+ bool null() override
+ {
+ events.push_back("null()");
+ return true;
+ }
+
+ bool boolean(bool val) override
+ {
+ events.push_back("boolean(val=" + std::string(val ? "true" : "false") + ")");
+ return true;
+ }
+
+ bool number_integer(number_integer_t val) override
+ {
+ events.push_back("number_integer(val=" + std::to_string(val) + ")");
+ return true;
+ }
+
+ bool number_unsigned(number_unsigned_t val) override
+ {
+ events.push_back("number_unsigned(val=" + std::to_string(val) + ")");
+ return true;
+ }
+
+ bool number_float(number_float_t val, const string_t& s) override
+ {
+ events.push_back("number_float(val=" + std::to_string(val) + ", s=" + s + ")");
+ return true;
+ }
+
+ bool string(string_t& val) override
+ {
+ events.push_back("string(val=" + val + ")");
+ return true;
+ }
+
+ bool start_object(std::size_t elements) override
+ {
+ events.push_back("start_object(elements=" + std::to_string(elements) + ")");
+ return true;
+ }
+
+ bool end_object() override
+ {
+ events.push_back("end_object()");
+ return true;
+ }
+
+ bool start_array(std::size_t elements) override
+ {
+ events.push_back("start_array(elements=" + std::to_string(elements) + ")");
+ return true;
+ }
+
+ bool end_array() override
+ {
+ events.push_back("end_array()");
+ return true;
+ }
+
+ bool key(string_t& val) override
+ {
+ events.push_back("key(val=" + val + ")");
+ return true;
+ }
+
+ bool binary(json::binary_t& val) override
+ {
+ events.push_back("binary(val=[...])");
+ return true;
+ }
+
+ bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override
+ {
+ events.push_back("parse_error(position=" + std::to_string(position) + ", last_token=" + last_token + ",\n ex=" + std::string(ex.what()) + ")");
+ return false;
+ }
+};
+
+int main()
+{
+ // a JSON text
+ auto text = R"(
+ {
+ "Image": {
+ "Width": 800,
+ "Height": 600,
+ "Title": "View from 15th Floor",
+ "Thumbnail": {
+ "Url": "http://www.example.com/image/481989943",
+ "Height": 125,
+ "Width": 100
+ },
+ "Animated" : false,
+ "IDs": [116, 943, 234, -38793],
+ "DeletionDate": null,
+ "Distance": 12.723374634
+ }
+ }]
+ )";
+
+ // create a SAX event consumer object
+ sax_event_consumer sec;
+
+ // parse JSON
+ bool result = json::sax_parse(text, &sec);
+
+ // output the recorded events
+ for (auto& event : sec.events)
+ {
+ std::cout << event << "\n";
+ }
+
+ // output the result of sax_parse
+ std::cout << "\nresult: " << std::boolalpha << result << std::endl;
+}
+Output:
start_object(elements=18446744073709551615)
+key(val=Image)
+start_object(elements=18446744073709551615)
+key(val=Width)
+number_unsigned(val=800)
+key(val=Height)
+number_unsigned(val=600)
+key(val=Title)
+string(val=View from 15th Floor)
+key(val=Thumbnail)
+start_object(elements=18446744073709551615)
+key(val=Url)
+string(val=http://www.example.com/image/481989943)
+key(val=Height)
+number_unsigned(val=125)
+key(val=Width)
+number_unsigned(val=100)
+end_object()
+key(val=Animated)
+boolean(val=false)
+key(val=IDs)
+start_array(elements=18446744073709551615)
+number_unsigned(val=116)
+number_unsigned(val=943)
+number_unsigned(val=234)
+number_integer(val=-38793)
+end_array()
+key(val=DeletionDate)
+null()
+key(val=Distance)
+number_float(val=12.723375, s=12.723374634)
+end_object()
+end_object()
+parse_error(position=460, last_token=12.723374634<U+000A> }<U+000A> }],
+ ex=[json.exception.parse_error.101] parse error at line 17, column 6: syntax error while parsing value - unexpected ']'; expected end of input)
+
+result: false
+virtual bool end_object() = 0;
+The end of an object was read.
Whether parsing should proceed.
The example below shows how the SAX interface is used.
#include <iostream>
+#include <iomanip>
+#include <sstream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+// a simple event consumer that collects string representations of the passed
+// values; note inheriting from json::json_sax_t is not required, but can
+// help not to forget a required function
+class sax_event_consumer : public json::json_sax_t
+{
+ public:
+ std::vector<std::string> events;
+
+ bool null() override
+ {
+ events.push_back("null()");
+ return true;
+ }
+
+ bool boolean(bool val) override
+ {
+ events.push_back("boolean(val=" + std::string(val ? "true" : "false") + ")");
+ return true;
+ }
+
+ bool number_integer(number_integer_t val) override
+ {
+ events.push_back("number_integer(val=" + std::to_string(val) + ")");
+ return true;
+ }
+
+ bool number_unsigned(number_unsigned_t val) override
+ {
+ events.push_back("number_unsigned(val=" + std::to_string(val) + ")");
+ return true;
+ }
+
+ bool number_float(number_float_t val, const string_t& s) override
+ {
+ events.push_back("number_float(val=" + std::to_string(val) + ", s=" + s + ")");
+ return true;
+ }
+
+ bool string(string_t& val) override
+ {
+ events.push_back("string(val=" + val + ")");
+ return true;
+ }
+
+ bool start_object(std::size_t elements) override
+ {
+ events.push_back("start_object(elements=" + std::to_string(elements) + ")");
+ return true;
+ }
+
+ bool end_object() override
+ {
+ events.push_back("end_object()");
+ return true;
+ }
+
+ bool start_array(std::size_t elements) override
+ {
+ events.push_back("start_array(elements=" + std::to_string(elements) + ")");
+ return true;
+ }
+
+ bool end_array() override
+ {
+ events.push_back("end_array()");
+ return true;
+ }
+
+ bool key(string_t& val) override
+ {
+ events.push_back("key(val=" + val + ")");
+ return true;
+ }
+
+ bool binary(json::binary_t& val) override
+ {
+ events.push_back("binary(val=[...])");
+ return true;
+ }
+
+ bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override
+ {
+ events.push_back("parse_error(position=" + std::to_string(position) + ", last_token=" + last_token + ",\n ex=" + std::string(ex.what()) + ")");
+ return false;
+ }
+};
+
+int main()
+{
+ // a JSON text
+ auto text = R"(
+ {
+ "Image": {
+ "Width": 800,
+ "Height": 600,
+ "Title": "View from 15th Floor",
+ "Thumbnail": {
+ "Url": "http://www.example.com/image/481989943",
+ "Height": 125,
+ "Width": 100
+ },
+ "Animated" : false,
+ "IDs": [116, 943, 234, -38793],
+ "DeletionDate": null,
+ "Distance": 12.723374634
+ }
+ }]
+ )";
+
+ // create a SAX event consumer object
+ sax_event_consumer sec;
+
+ // parse JSON
+ bool result = json::sax_parse(text, &sec);
+
+ // output the recorded events
+ for (auto& event : sec.events)
+ {
+ std::cout << event << "\n";
+ }
+
+ // output the result of sax_parse
+ std::cout << "\nresult: " << std::boolalpha << result << std::endl;
+}
+Output:
start_object(elements=18446744073709551615)
+key(val=Image)
+start_object(elements=18446744073709551615)
+key(val=Width)
+number_unsigned(val=800)
+key(val=Height)
+number_unsigned(val=600)
+key(val=Title)
+string(val=View from 15th Floor)
+key(val=Thumbnail)
+start_object(elements=18446744073709551615)
+key(val=Url)
+string(val=http://www.example.com/image/481989943)
+key(val=Height)
+number_unsigned(val=125)
+key(val=Width)
+number_unsigned(val=100)
+end_object()
+key(val=Animated)
+boolean(val=false)
+key(val=IDs)
+start_array(elements=18446744073709551615)
+number_unsigned(val=116)
+number_unsigned(val=943)
+number_unsigned(val=234)
+number_integer(val=-38793)
+end_array()
+key(val=DeletionDate)
+null()
+key(val=Distance)
+number_float(val=12.723375, s=12.723374634)
+end_object()
+end_object()
+parse_error(position=460, last_token=12.723374634<U+000A> }<U+000A> }],
+ ex=[json.exception.parse_error.101] parse error at line 17, column 6: syntax error while parsing value - unexpected ']'; expected end of input)
+
+result: false
+template<typename BasicJsonType>
+struct json_sax;
+This class describes the SAX interface used by sax_parse. Each function is called in different situations while the input is parsed. The boolean return value informs the parser whether to continue processing the input.
BasicJsonTypebasic_jsonBasicJsonType's type for numbers (integer)BasicJsonType's type for numbers (unsigned)BasicJsonType's type for numbers (floating-point)BasicJsonType's type for stringsBasicJsonType's type for binary arraysbinary_t, binary) added in version 3.8.0.virtual bool key(string_t& val) = 0;
+An object key was read.
val (in)Whether parsing should proceed.
It is safe to move the passed object key value.
The example below shows how the SAX interface is used.
#include <iostream>
+#include <iomanip>
+#include <sstream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+// a simple event consumer that collects string representations of the passed
+// values; note inheriting from json::json_sax_t is not required, but can
+// help not to forget a required function
+class sax_event_consumer : public json::json_sax_t
+{
+ public:
+ std::vector<std::string> events;
+
+ bool null() override
+ {
+ events.push_back("null()");
+ return true;
+ }
+
+ bool boolean(bool val) override
+ {
+ events.push_back("boolean(val=" + std::string(val ? "true" : "false") + ")");
+ return true;
+ }
+
+ bool number_integer(number_integer_t val) override
+ {
+ events.push_back("number_integer(val=" + std::to_string(val) + ")");
+ return true;
+ }
+
+ bool number_unsigned(number_unsigned_t val) override
+ {
+ events.push_back("number_unsigned(val=" + std::to_string(val) + ")");
+ return true;
+ }
+
+ bool number_float(number_float_t val, const string_t& s) override
+ {
+ events.push_back("number_float(val=" + std::to_string(val) + ", s=" + s + ")");
+ return true;
+ }
+
+ bool string(string_t& val) override
+ {
+ events.push_back("string(val=" + val + ")");
+ return true;
+ }
+
+ bool start_object(std::size_t elements) override
+ {
+ events.push_back("start_object(elements=" + std::to_string(elements) + ")");
+ return true;
+ }
+
+ bool end_object() override
+ {
+ events.push_back("end_object()");
+ return true;
+ }
+
+ bool start_array(std::size_t elements) override
+ {
+ events.push_back("start_array(elements=" + std::to_string(elements) + ")");
+ return true;
+ }
+
+ bool end_array() override
+ {
+ events.push_back("end_array()");
+ return true;
+ }
+
+ bool key(string_t& val) override
+ {
+ events.push_back("key(val=" + val + ")");
+ return true;
+ }
+
+ bool binary(json::binary_t& val) override
+ {
+ events.push_back("binary(val=[...])");
+ return true;
+ }
+
+ bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override
+ {
+ events.push_back("parse_error(position=" + std::to_string(position) + ", last_token=" + last_token + ",\n ex=" + std::string(ex.what()) + ")");
+ return false;
+ }
+};
+
+int main()
+{
+ // a JSON text
+ auto text = R"(
+ {
+ "Image": {
+ "Width": 800,
+ "Height": 600,
+ "Title": "View from 15th Floor",
+ "Thumbnail": {
+ "Url": "http://www.example.com/image/481989943",
+ "Height": 125,
+ "Width": 100
+ },
+ "Animated" : false,
+ "IDs": [116, 943, 234, -38793],
+ "DeletionDate": null,
+ "Distance": 12.723374634
+ }
+ }]
+ )";
+
+ // create a SAX event consumer object
+ sax_event_consumer sec;
+
+ // parse JSON
+ bool result = json::sax_parse(text, &sec);
+
+ // output the recorded events
+ for (auto& event : sec.events)
+ {
+ std::cout << event << "\n";
+ }
+
+ // output the result of sax_parse
+ std::cout << "\nresult: " << std::boolalpha << result << std::endl;
+}
+Output:
start_object(elements=18446744073709551615)
+key(val=Image)
+start_object(elements=18446744073709551615)
+key(val=Width)
+number_unsigned(val=800)
+key(val=Height)
+number_unsigned(val=600)
+key(val=Title)
+string(val=View from 15th Floor)
+key(val=Thumbnail)
+start_object(elements=18446744073709551615)
+key(val=Url)
+string(val=http://www.example.com/image/481989943)
+key(val=Height)
+number_unsigned(val=125)
+key(val=Width)
+number_unsigned(val=100)
+end_object()
+key(val=Animated)
+boolean(val=false)
+key(val=IDs)
+start_array(elements=18446744073709551615)
+number_unsigned(val=116)
+number_unsigned(val=943)
+number_unsigned(val=234)
+number_integer(val=-38793)
+end_array()
+key(val=DeletionDate)
+null()
+key(val=Distance)
+number_float(val=12.723375, s=12.723374634)
+end_object()
+end_object()
+parse_error(position=460, last_token=12.723374634<U+000A> }<U+000A> }],
+ ex=[json.exception.parse_error.101] parse error at line 17, column 6: syntax error while parsing value - unexpected ']'; expected end of input)
+
+result: false
+virtual bool null() = 0;
+A null value was read.
Whether parsing should proceed.
The example below shows how the SAX interface is used.
#include <iostream>
+#include <iomanip>
+#include <sstream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+// a simple event consumer that collects string representations of the passed
+// values; note inheriting from json::json_sax_t is not required, but can
+// help not to forget a required function
+class sax_event_consumer : public json::json_sax_t
+{
+ public:
+ std::vector<std::string> events;
+
+ bool null() override
+ {
+ events.push_back("null()");
+ return true;
+ }
+
+ bool boolean(bool val) override
+ {
+ events.push_back("boolean(val=" + std::string(val ? "true" : "false") + ")");
+ return true;
+ }
+
+ bool number_integer(number_integer_t val) override
+ {
+ events.push_back("number_integer(val=" + std::to_string(val) + ")");
+ return true;
+ }
+
+ bool number_unsigned(number_unsigned_t val) override
+ {
+ events.push_back("number_unsigned(val=" + std::to_string(val) + ")");
+ return true;
+ }
+
+ bool number_float(number_float_t val, const string_t& s) override
+ {
+ events.push_back("number_float(val=" + std::to_string(val) + ", s=" + s + ")");
+ return true;
+ }
+
+ bool string(string_t& val) override
+ {
+ events.push_back("string(val=" + val + ")");
+ return true;
+ }
+
+ bool start_object(std::size_t elements) override
+ {
+ events.push_back("start_object(elements=" + std::to_string(elements) + ")");
+ return true;
+ }
+
+ bool end_object() override
+ {
+ events.push_back("end_object()");
+ return true;
+ }
+
+ bool start_array(std::size_t elements) override
+ {
+ events.push_back("start_array(elements=" + std::to_string(elements) + ")");
+ return true;
+ }
+
+ bool end_array() override
+ {
+ events.push_back("end_array()");
+ return true;
+ }
+
+ bool key(string_t& val) override
+ {
+ events.push_back("key(val=" + val + ")");
+ return true;
+ }
+
+ bool binary(json::binary_t& val) override
+ {
+ events.push_back("binary(val=[...])");
+ return true;
+ }
+
+ bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override
+ {
+ events.push_back("parse_error(position=" + std::to_string(position) + ", last_token=" + last_token + ",\n ex=" + std::string(ex.what()) + ")");
+ return false;
+ }
+};
+
+int main()
+{
+ // a JSON text
+ auto text = R"(
+ {
+ "Image": {
+ "Width": 800,
+ "Height": 600,
+ "Title": "View from 15th Floor",
+ "Thumbnail": {
+ "Url": "http://www.example.com/image/481989943",
+ "Height": 125,
+ "Width": 100
+ },
+ "Animated" : false,
+ "IDs": [116, 943, 234, -38793],
+ "DeletionDate": null,
+ "Distance": 12.723374634
+ }
+ }]
+ )";
+
+ // create a SAX event consumer object
+ sax_event_consumer sec;
+
+ // parse JSON
+ bool result = json::sax_parse(text, &sec);
+
+ // output the recorded events
+ for (auto& event : sec.events)
+ {
+ std::cout << event << "\n";
+ }
+
+ // output the result of sax_parse
+ std::cout << "\nresult: " << std::boolalpha << result << std::endl;
+}
+Output:
start_object(elements=18446744073709551615)
+key(val=Image)
+start_object(elements=18446744073709551615)
+key(val=Width)
+number_unsigned(val=800)
+key(val=Height)
+number_unsigned(val=600)
+key(val=Title)
+string(val=View from 15th Floor)
+key(val=Thumbnail)
+start_object(elements=18446744073709551615)
+key(val=Url)
+string(val=http://www.example.com/image/481989943)
+key(val=Height)
+number_unsigned(val=125)
+key(val=Width)
+number_unsigned(val=100)
+end_object()
+key(val=Animated)
+boolean(val=false)
+key(val=IDs)
+start_array(elements=18446744073709551615)
+number_unsigned(val=116)
+number_unsigned(val=943)
+number_unsigned(val=234)
+number_integer(val=-38793)
+end_array()
+key(val=DeletionDate)
+null()
+key(val=Distance)
+number_float(val=12.723375, s=12.723374634)
+end_object()
+end_object()
+parse_error(position=460, last_token=12.723374634<U+000A> }<U+000A> }],
+ ex=[json.exception.parse_error.101] parse error at line 17, column 6: syntax error while parsing value - unexpected ']'; expected end of input)
+
+result: false
+virtual bool number_float(number_float_t val, const string_t& s) = 0;
+A floating-point number was read.
val (in)s (in)Whether parsing should proceed.
The example below shows how the SAX interface is used.
#include <iostream>
+#include <iomanip>
+#include <sstream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+// a simple event consumer that collects string representations of the passed
+// values; note inheriting from json::json_sax_t is not required, but can
+// help not to forget a required function
+class sax_event_consumer : public json::json_sax_t
+{
+ public:
+ std::vector<std::string> events;
+
+ bool null() override
+ {
+ events.push_back("null()");
+ return true;
+ }
+
+ bool boolean(bool val) override
+ {
+ events.push_back("boolean(val=" + std::string(val ? "true" : "false") + ")");
+ return true;
+ }
+
+ bool number_integer(number_integer_t val) override
+ {
+ events.push_back("number_integer(val=" + std::to_string(val) + ")");
+ return true;
+ }
+
+ bool number_unsigned(number_unsigned_t val) override
+ {
+ events.push_back("number_unsigned(val=" + std::to_string(val) + ")");
+ return true;
+ }
+
+ bool number_float(number_float_t val, const string_t& s) override
+ {
+ events.push_back("number_float(val=" + std::to_string(val) + ", s=" + s + ")");
+ return true;
+ }
+
+ bool string(string_t& val) override
+ {
+ events.push_back("string(val=" + val + ")");
+ return true;
+ }
+
+ bool start_object(std::size_t elements) override
+ {
+ events.push_back("start_object(elements=" + std::to_string(elements) + ")");
+ return true;
+ }
+
+ bool end_object() override
+ {
+ events.push_back("end_object()");
+ return true;
+ }
+
+ bool start_array(std::size_t elements) override
+ {
+ events.push_back("start_array(elements=" + std::to_string(elements) + ")");
+ return true;
+ }
+
+ bool end_array() override
+ {
+ events.push_back("end_array()");
+ return true;
+ }
+
+ bool key(string_t& val) override
+ {
+ events.push_back("key(val=" + val + ")");
+ return true;
+ }
+
+ bool binary(json::binary_t& val) override
+ {
+ events.push_back("binary(val=[...])");
+ return true;
+ }
+
+ bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override
+ {
+ events.push_back("parse_error(position=" + std::to_string(position) + ", last_token=" + last_token + ",\n ex=" + std::string(ex.what()) + ")");
+ return false;
+ }
+};
+
+int main()
+{
+ // a JSON text
+ auto text = R"(
+ {
+ "Image": {
+ "Width": 800,
+ "Height": 600,
+ "Title": "View from 15th Floor",
+ "Thumbnail": {
+ "Url": "http://www.example.com/image/481989943",
+ "Height": 125,
+ "Width": 100
+ },
+ "Animated" : false,
+ "IDs": [116, 943, 234, -38793],
+ "DeletionDate": null,
+ "Distance": 12.723374634
+ }
+ }]
+ )";
+
+ // create a SAX event consumer object
+ sax_event_consumer sec;
+
+ // parse JSON
+ bool result = json::sax_parse(text, &sec);
+
+ // output the recorded events
+ for (auto& event : sec.events)
+ {
+ std::cout << event << "\n";
+ }
+
+ // output the result of sax_parse
+ std::cout << "\nresult: " << std::boolalpha << result << std::endl;
+}
+Output:
start_object(elements=18446744073709551615)
+key(val=Image)
+start_object(elements=18446744073709551615)
+key(val=Width)
+number_unsigned(val=800)
+key(val=Height)
+number_unsigned(val=600)
+key(val=Title)
+string(val=View from 15th Floor)
+key(val=Thumbnail)
+start_object(elements=18446744073709551615)
+key(val=Url)
+string(val=http://www.example.com/image/481989943)
+key(val=Height)
+number_unsigned(val=125)
+key(val=Width)
+number_unsigned(val=100)
+end_object()
+key(val=Animated)
+boolean(val=false)
+key(val=IDs)
+start_array(elements=18446744073709551615)
+number_unsigned(val=116)
+number_unsigned(val=943)
+number_unsigned(val=234)
+number_integer(val=-38793)
+end_array()
+key(val=DeletionDate)
+null()
+key(val=Distance)
+number_float(val=12.723375, s=12.723374634)
+end_object()
+end_object()
+parse_error(position=460, last_token=12.723374634<U+000A> }<U+000A> }],
+ ex=[json.exception.parse_error.101] parse error at line 17, column 6: syntax error while parsing value - unexpected ']'; expected end of input)
+
+result: false
+virtual bool number_integer(number_integer_t val) = 0;
+An integer number was read.
val (in)Whether parsing should proceed.
The example below shows how the SAX interface is used.
#include <iostream>
+#include <iomanip>
+#include <sstream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+// a simple event consumer that collects string representations of the passed
+// values; note inheriting from json::json_sax_t is not required, but can
+// help not to forget a required function
+class sax_event_consumer : public json::json_sax_t
+{
+ public:
+ std::vector<std::string> events;
+
+ bool null() override
+ {
+ events.push_back("null()");
+ return true;
+ }
+
+ bool boolean(bool val) override
+ {
+ events.push_back("boolean(val=" + std::string(val ? "true" : "false") + ")");
+ return true;
+ }
+
+ bool number_integer(number_integer_t val) override
+ {
+ events.push_back("number_integer(val=" + std::to_string(val) + ")");
+ return true;
+ }
+
+ bool number_unsigned(number_unsigned_t val) override
+ {
+ events.push_back("number_unsigned(val=" + std::to_string(val) + ")");
+ return true;
+ }
+
+ bool number_float(number_float_t val, const string_t& s) override
+ {
+ events.push_back("number_float(val=" + std::to_string(val) + ", s=" + s + ")");
+ return true;
+ }
+
+ bool string(string_t& val) override
+ {
+ events.push_back("string(val=" + val + ")");
+ return true;
+ }
+
+ bool start_object(std::size_t elements) override
+ {
+ events.push_back("start_object(elements=" + std::to_string(elements) + ")");
+ return true;
+ }
+
+ bool end_object() override
+ {
+ events.push_back("end_object()");
+ return true;
+ }
+
+ bool start_array(std::size_t elements) override
+ {
+ events.push_back("start_array(elements=" + std::to_string(elements) + ")");
+ return true;
+ }
+
+ bool end_array() override
+ {
+ events.push_back("end_array()");
+ return true;
+ }
+
+ bool key(string_t& val) override
+ {
+ events.push_back("key(val=" + val + ")");
+ return true;
+ }
+
+ bool binary(json::binary_t& val) override
+ {
+ events.push_back("binary(val=[...])");
+ return true;
+ }
+
+ bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override
+ {
+ events.push_back("parse_error(position=" + std::to_string(position) + ", last_token=" + last_token + ",\n ex=" + std::string(ex.what()) + ")");
+ return false;
+ }
+};
+
+int main()
+{
+ // a JSON text
+ auto text = R"(
+ {
+ "Image": {
+ "Width": 800,
+ "Height": 600,
+ "Title": "View from 15th Floor",
+ "Thumbnail": {
+ "Url": "http://www.example.com/image/481989943",
+ "Height": 125,
+ "Width": 100
+ },
+ "Animated" : false,
+ "IDs": [116, 943, 234, -38793],
+ "DeletionDate": null,
+ "Distance": 12.723374634
+ }
+ }]
+ )";
+
+ // create a SAX event consumer object
+ sax_event_consumer sec;
+
+ // parse JSON
+ bool result = json::sax_parse(text, &sec);
+
+ // output the recorded events
+ for (auto& event : sec.events)
+ {
+ std::cout << event << "\n";
+ }
+
+ // output the result of sax_parse
+ std::cout << "\nresult: " << std::boolalpha << result << std::endl;
+}
+Output:
start_object(elements=18446744073709551615)
+key(val=Image)
+start_object(elements=18446744073709551615)
+key(val=Width)
+number_unsigned(val=800)
+key(val=Height)
+number_unsigned(val=600)
+key(val=Title)
+string(val=View from 15th Floor)
+key(val=Thumbnail)
+start_object(elements=18446744073709551615)
+key(val=Url)
+string(val=http://www.example.com/image/481989943)
+key(val=Height)
+number_unsigned(val=125)
+key(val=Width)
+number_unsigned(val=100)
+end_object()
+key(val=Animated)
+boolean(val=false)
+key(val=IDs)
+start_array(elements=18446744073709551615)
+number_unsigned(val=116)
+number_unsigned(val=943)
+number_unsigned(val=234)
+number_integer(val=-38793)
+end_array()
+key(val=DeletionDate)
+null()
+key(val=Distance)
+number_float(val=12.723375, s=12.723374634)
+end_object()
+end_object()
+parse_error(position=460, last_token=12.723374634<U+000A> }<U+000A> }],
+ ex=[json.exception.parse_error.101] parse error at line 17, column 6: syntax error while parsing value - unexpected ']'; expected end of input)
+
+result: false
+virtual bool number_unsigned(number_unsigned_t val) = 0;
+An unsigned integer number was read.
val (in)Whether parsing should proceed.
The example below shows how the SAX interface is used.
#include <iostream>
+#include <iomanip>
+#include <sstream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+// a simple event consumer that collects string representations of the passed
+// values; note inheriting from json::json_sax_t is not required, but can
+// help not to forget a required function
+class sax_event_consumer : public json::json_sax_t
+{
+ public:
+ std::vector<std::string> events;
+
+ bool null() override
+ {
+ events.push_back("null()");
+ return true;
+ }
+
+ bool boolean(bool val) override
+ {
+ events.push_back("boolean(val=" + std::string(val ? "true" : "false") + ")");
+ return true;
+ }
+
+ bool number_integer(number_integer_t val) override
+ {
+ events.push_back("number_integer(val=" + std::to_string(val) + ")");
+ return true;
+ }
+
+ bool number_unsigned(number_unsigned_t val) override
+ {
+ events.push_back("number_unsigned(val=" + std::to_string(val) + ")");
+ return true;
+ }
+
+ bool number_float(number_float_t val, const string_t& s) override
+ {
+ events.push_back("number_float(val=" + std::to_string(val) + ", s=" + s + ")");
+ return true;
+ }
+
+ bool string(string_t& val) override
+ {
+ events.push_back("string(val=" + val + ")");
+ return true;
+ }
+
+ bool start_object(std::size_t elements) override
+ {
+ events.push_back("start_object(elements=" + std::to_string(elements) + ")");
+ return true;
+ }
+
+ bool end_object() override
+ {
+ events.push_back("end_object()");
+ return true;
+ }
+
+ bool start_array(std::size_t elements) override
+ {
+ events.push_back("start_array(elements=" + std::to_string(elements) + ")");
+ return true;
+ }
+
+ bool end_array() override
+ {
+ events.push_back("end_array()");
+ return true;
+ }
+
+ bool key(string_t& val) override
+ {
+ events.push_back("key(val=" + val + ")");
+ return true;
+ }
+
+ bool binary(json::binary_t& val) override
+ {
+ events.push_back("binary(val=[...])");
+ return true;
+ }
+
+ bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override
+ {
+ events.push_back("parse_error(position=" + std::to_string(position) + ", last_token=" + last_token + ",\n ex=" + std::string(ex.what()) + ")");
+ return false;
+ }
+};
+
+int main()
+{
+ // a JSON text
+ auto text = R"(
+ {
+ "Image": {
+ "Width": 800,
+ "Height": 600,
+ "Title": "View from 15th Floor",
+ "Thumbnail": {
+ "Url": "http://www.example.com/image/481989943",
+ "Height": 125,
+ "Width": 100
+ },
+ "Animated" : false,
+ "IDs": [116, 943, 234, -38793],
+ "DeletionDate": null,
+ "Distance": 12.723374634
+ }
+ }]
+ )";
+
+ // create a SAX event consumer object
+ sax_event_consumer sec;
+
+ // parse JSON
+ bool result = json::sax_parse(text, &sec);
+
+ // output the recorded events
+ for (auto& event : sec.events)
+ {
+ std::cout << event << "\n";
+ }
+
+ // output the result of sax_parse
+ std::cout << "\nresult: " << std::boolalpha << result << std::endl;
+}
+Output:
start_object(elements=18446744073709551615)
+key(val=Image)
+start_object(elements=18446744073709551615)
+key(val=Width)
+number_unsigned(val=800)
+key(val=Height)
+number_unsigned(val=600)
+key(val=Title)
+string(val=View from 15th Floor)
+key(val=Thumbnail)
+start_object(elements=18446744073709551615)
+key(val=Url)
+string(val=http://www.example.com/image/481989943)
+key(val=Height)
+number_unsigned(val=125)
+key(val=Width)
+number_unsigned(val=100)
+end_object()
+key(val=Animated)
+boolean(val=false)
+key(val=IDs)
+start_array(elements=18446744073709551615)
+number_unsigned(val=116)
+number_unsigned(val=943)
+number_unsigned(val=234)
+number_integer(val=-38793)
+end_array()
+key(val=DeletionDate)
+null()
+key(val=Distance)
+number_float(val=12.723375, s=12.723374634)
+end_object()
+end_object()
+parse_error(position=460, last_token=12.723374634<U+000A> }<U+000A> }],
+ ex=[json.exception.parse_error.101] parse error at line 17, column 6: syntax error while parsing value - unexpected ']'; expected end of input)
+
+result: false
+virtual bool parse_error(std::size_t position,
+ const std::string& last_token,
+ const detail::exception& ex) = 0;
+A parse error occurred.
position (in)last_token (in)ex (in)Whether parsing should proceed (must return false).
The example below shows how the SAX interface is used.
#include <iostream>
+#include <iomanip>
+#include <sstream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+// a simple event consumer that collects string representations of the passed
+// values; note inheriting from json::json_sax_t is not required, but can
+// help not to forget a required function
+class sax_event_consumer : public json::json_sax_t
+{
+ public:
+ std::vector<std::string> events;
+
+ bool null() override
+ {
+ events.push_back("null()");
+ return true;
+ }
+
+ bool boolean(bool val) override
+ {
+ events.push_back("boolean(val=" + std::string(val ? "true" : "false") + ")");
+ return true;
+ }
+
+ bool number_integer(number_integer_t val) override
+ {
+ events.push_back("number_integer(val=" + std::to_string(val) + ")");
+ return true;
+ }
+
+ bool number_unsigned(number_unsigned_t val) override
+ {
+ events.push_back("number_unsigned(val=" + std::to_string(val) + ")");
+ return true;
+ }
+
+ bool number_float(number_float_t val, const string_t& s) override
+ {
+ events.push_back("number_float(val=" + std::to_string(val) + ", s=" + s + ")");
+ return true;
+ }
+
+ bool string(string_t& val) override
+ {
+ events.push_back("string(val=" + val + ")");
+ return true;
+ }
+
+ bool start_object(std::size_t elements) override
+ {
+ events.push_back("start_object(elements=" + std::to_string(elements) + ")");
+ return true;
+ }
+
+ bool end_object() override
+ {
+ events.push_back("end_object()");
+ return true;
+ }
+
+ bool start_array(std::size_t elements) override
+ {
+ events.push_back("start_array(elements=" + std::to_string(elements) + ")");
+ return true;
+ }
+
+ bool end_array() override
+ {
+ events.push_back("end_array()");
+ return true;
+ }
+
+ bool key(string_t& val) override
+ {
+ events.push_back("key(val=" + val + ")");
+ return true;
+ }
+
+ bool binary(json::binary_t& val) override
+ {
+ events.push_back("binary(val=[...])");
+ return true;
+ }
+
+ bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override
+ {
+ events.push_back("parse_error(position=" + std::to_string(position) + ", last_token=" + last_token + ",\n ex=" + std::string(ex.what()) + ")");
+ return false;
+ }
+};
+
+int main()
+{
+ // a JSON text
+ auto text = R"(
+ {
+ "Image": {
+ "Width": 800,
+ "Height": 600,
+ "Title": "View from 15th Floor",
+ "Thumbnail": {
+ "Url": "http://www.example.com/image/481989943",
+ "Height": 125,
+ "Width": 100
+ },
+ "Animated" : false,
+ "IDs": [116, 943, 234, -38793],
+ "DeletionDate": null,
+ "Distance": 12.723374634
+ }
+ }]
+ )";
+
+ // create a SAX event consumer object
+ sax_event_consumer sec;
+
+ // parse JSON
+ bool result = json::sax_parse(text, &sec);
+
+ // output the recorded events
+ for (auto& event : sec.events)
+ {
+ std::cout << event << "\n";
+ }
+
+ // output the result of sax_parse
+ std::cout << "\nresult: " << std::boolalpha << result << std::endl;
+}
+Output:
start_object(elements=18446744073709551615)
+key(val=Image)
+start_object(elements=18446744073709551615)
+key(val=Width)
+number_unsigned(val=800)
+key(val=Height)
+number_unsigned(val=600)
+key(val=Title)
+string(val=View from 15th Floor)
+key(val=Thumbnail)
+start_object(elements=18446744073709551615)
+key(val=Url)
+string(val=http://www.example.com/image/481989943)
+key(val=Height)
+number_unsigned(val=125)
+key(val=Width)
+number_unsigned(val=100)
+end_object()
+key(val=Animated)
+boolean(val=false)
+key(val=IDs)
+start_array(elements=18446744073709551615)
+number_unsigned(val=116)
+number_unsigned(val=943)
+number_unsigned(val=234)
+number_integer(val=-38793)
+end_array()
+key(val=DeletionDate)
+null()
+key(val=Distance)
+number_float(val=12.723375, s=12.723374634)
+end_object()
+end_object()
+parse_error(position=460, last_token=12.723374634<U+000A> }<U+000A> }],
+ ex=[json.exception.parse_error.101] parse error at line 17, column 6: syntax error while parsing value - unexpected ']'; expected end of input)
+
+result: false
+virtual bool start_array(std::size_t elements) = 0;
+The beginning of an array was read.
elements (in)-1 if unknownWhether parsing should proceed.
Binary formats may report the number of elements.
The example below shows how the SAX interface is used.
#include <iostream>
+#include <iomanip>
+#include <sstream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+// a simple event consumer that collects string representations of the passed
+// values; note inheriting from json::json_sax_t is not required, but can
+// help not to forget a required function
+class sax_event_consumer : public json::json_sax_t
+{
+ public:
+ std::vector<std::string> events;
+
+ bool null() override
+ {
+ events.push_back("null()");
+ return true;
+ }
+
+ bool boolean(bool val) override
+ {
+ events.push_back("boolean(val=" + std::string(val ? "true" : "false") + ")");
+ return true;
+ }
+
+ bool number_integer(number_integer_t val) override
+ {
+ events.push_back("number_integer(val=" + std::to_string(val) + ")");
+ return true;
+ }
+
+ bool number_unsigned(number_unsigned_t val) override
+ {
+ events.push_back("number_unsigned(val=" + std::to_string(val) + ")");
+ return true;
+ }
+
+ bool number_float(number_float_t val, const string_t& s) override
+ {
+ events.push_back("number_float(val=" + std::to_string(val) + ", s=" + s + ")");
+ return true;
+ }
+
+ bool string(string_t& val) override
+ {
+ events.push_back("string(val=" + val + ")");
+ return true;
+ }
+
+ bool start_object(std::size_t elements) override
+ {
+ events.push_back("start_object(elements=" + std::to_string(elements) + ")");
+ return true;
+ }
+
+ bool end_object() override
+ {
+ events.push_back("end_object()");
+ return true;
+ }
+
+ bool start_array(std::size_t elements) override
+ {
+ events.push_back("start_array(elements=" + std::to_string(elements) + ")");
+ return true;
+ }
+
+ bool end_array() override
+ {
+ events.push_back("end_array()");
+ return true;
+ }
+
+ bool key(string_t& val) override
+ {
+ events.push_back("key(val=" + val + ")");
+ return true;
+ }
+
+ bool binary(json::binary_t& val) override
+ {
+ events.push_back("binary(val=[...])");
+ return true;
+ }
+
+ bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override
+ {
+ events.push_back("parse_error(position=" + std::to_string(position) + ", last_token=" + last_token + ",\n ex=" + std::string(ex.what()) + ")");
+ return false;
+ }
+};
+
+int main()
+{
+ // a JSON text
+ auto text = R"(
+ {
+ "Image": {
+ "Width": 800,
+ "Height": 600,
+ "Title": "View from 15th Floor",
+ "Thumbnail": {
+ "Url": "http://www.example.com/image/481989943",
+ "Height": 125,
+ "Width": 100
+ },
+ "Animated" : false,
+ "IDs": [116, 943, 234, -38793],
+ "DeletionDate": null,
+ "Distance": 12.723374634
+ }
+ }]
+ )";
+
+ // create a SAX event consumer object
+ sax_event_consumer sec;
+
+ // parse JSON
+ bool result = json::sax_parse(text, &sec);
+
+ // output the recorded events
+ for (auto& event : sec.events)
+ {
+ std::cout << event << "\n";
+ }
+
+ // output the result of sax_parse
+ std::cout << "\nresult: " << std::boolalpha << result << std::endl;
+}
+Output:
start_object(elements=18446744073709551615)
+key(val=Image)
+start_object(elements=18446744073709551615)
+key(val=Width)
+number_unsigned(val=800)
+key(val=Height)
+number_unsigned(val=600)
+key(val=Title)
+string(val=View from 15th Floor)
+key(val=Thumbnail)
+start_object(elements=18446744073709551615)
+key(val=Url)
+string(val=http://www.example.com/image/481989943)
+key(val=Height)
+number_unsigned(val=125)
+key(val=Width)
+number_unsigned(val=100)
+end_object()
+key(val=Animated)
+boolean(val=false)
+key(val=IDs)
+start_array(elements=18446744073709551615)
+number_unsigned(val=116)
+number_unsigned(val=943)
+number_unsigned(val=234)
+number_integer(val=-38793)
+end_array()
+key(val=DeletionDate)
+null()
+key(val=Distance)
+number_float(val=12.723375, s=12.723374634)
+end_object()
+end_object()
+parse_error(position=460, last_token=12.723374634<U+000A> }<U+000A> }],
+ ex=[json.exception.parse_error.101] parse error at line 17, column 6: syntax error while parsing value - unexpected ']'; expected end of input)
+
+result: false
+virtual bool start_object(std::size_t elements) = 0;
+The beginning of an object was read.
elements (in)-1 if unknownWhether parsing should proceed.
Binary formats may report the number of elements.
The example below shows how the SAX interface is used.
#include <iostream>
+#include <iomanip>
+#include <sstream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+// a simple event consumer that collects string representations of the passed
+// values; note inheriting from json::json_sax_t is not required, but can
+// help not to forget a required function
+class sax_event_consumer : public json::json_sax_t
+{
+ public:
+ std::vector<std::string> events;
+
+ bool null() override
+ {
+ events.push_back("null()");
+ return true;
+ }
+
+ bool boolean(bool val) override
+ {
+ events.push_back("boolean(val=" + std::string(val ? "true" : "false") + ")");
+ return true;
+ }
+
+ bool number_integer(number_integer_t val) override
+ {
+ events.push_back("number_integer(val=" + std::to_string(val) + ")");
+ return true;
+ }
+
+ bool number_unsigned(number_unsigned_t val) override
+ {
+ events.push_back("number_unsigned(val=" + std::to_string(val) + ")");
+ return true;
+ }
+
+ bool number_float(number_float_t val, const string_t& s) override
+ {
+ events.push_back("number_float(val=" + std::to_string(val) + ", s=" + s + ")");
+ return true;
+ }
+
+ bool string(string_t& val) override
+ {
+ events.push_back("string(val=" + val + ")");
+ return true;
+ }
+
+ bool start_object(std::size_t elements) override
+ {
+ events.push_back("start_object(elements=" + std::to_string(elements) + ")");
+ return true;
+ }
+
+ bool end_object() override
+ {
+ events.push_back("end_object()");
+ return true;
+ }
+
+ bool start_array(std::size_t elements) override
+ {
+ events.push_back("start_array(elements=" + std::to_string(elements) + ")");
+ return true;
+ }
+
+ bool end_array() override
+ {
+ events.push_back("end_array()");
+ return true;
+ }
+
+ bool key(string_t& val) override
+ {
+ events.push_back("key(val=" + val + ")");
+ return true;
+ }
+
+ bool binary(json::binary_t& val) override
+ {
+ events.push_back("binary(val=[...])");
+ return true;
+ }
+
+ bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override
+ {
+ events.push_back("parse_error(position=" + std::to_string(position) + ", last_token=" + last_token + ",\n ex=" + std::string(ex.what()) + ")");
+ return false;
+ }
+};
+
+int main()
+{
+ // a JSON text
+ auto text = R"(
+ {
+ "Image": {
+ "Width": 800,
+ "Height": 600,
+ "Title": "View from 15th Floor",
+ "Thumbnail": {
+ "Url": "http://www.example.com/image/481989943",
+ "Height": 125,
+ "Width": 100
+ },
+ "Animated" : false,
+ "IDs": [116, 943, 234, -38793],
+ "DeletionDate": null,
+ "Distance": 12.723374634
+ }
+ }]
+ )";
+
+ // create a SAX event consumer object
+ sax_event_consumer sec;
+
+ // parse JSON
+ bool result = json::sax_parse(text, &sec);
+
+ // output the recorded events
+ for (auto& event : sec.events)
+ {
+ std::cout << event << "\n";
+ }
+
+ // output the result of sax_parse
+ std::cout << "\nresult: " << std::boolalpha << result << std::endl;
+}
+Output:
start_object(elements=18446744073709551615)
+key(val=Image)
+start_object(elements=18446744073709551615)
+key(val=Width)
+number_unsigned(val=800)
+key(val=Height)
+number_unsigned(val=600)
+key(val=Title)
+string(val=View from 15th Floor)
+key(val=Thumbnail)
+start_object(elements=18446744073709551615)
+key(val=Url)
+string(val=http://www.example.com/image/481989943)
+key(val=Height)
+number_unsigned(val=125)
+key(val=Width)
+number_unsigned(val=100)
+end_object()
+key(val=Animated)
+boolean(val=false)
+key(val=IDs)
+start_array(elements=18446744073709551615)
+number_unsigned(val=116)
+number_unsigned(val=943)
+number_unsigned(val=234)
+number_integer(val=-38793)
+end_array()
+key(val=DeletionDate)
+null()
+key(val=Distance)
+number_float(val=12.723375, s=12.723374634)
+end_object()
+end_object()
+parse_error(position=460, last_token=12.723374634<U+000A> }<U+000A> }],
+ ex=[json.exception.parse_error.101] parse error at line 17, column 6: syntax error while parsing value - unexpected ']'; expected end of input)
+
+result: false
+virtual bool string(string_t& val) = 0;
+A string value was read.
val (in)Whether parsing should proceed.
It is safe to move the passed string value.
The example below shows how the SAX interface is used.
#include <iostream>
+#include <iomanip>
+#include <sstream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+// a simple event consumer that collects string representations of the passed
+// values; note inheriting from json::json_sax_t is not required, but can
+// help not to forget a required function
+class sax_event_consumer : public json::json_sax_t
+{
+ public:
+ std::vector<std::string> events;
+
+ bool null() override
+ {
+ events.push_back("null()");
+ return true;
+ }
+
+ bool boolean(bool val) override
+ {
+ events.push_back("boolean(val=" + std::string(val ? "true" : "false") + ")");
+ return true;
+ }
+
+ bool number_integer(number_integer_t val) override
+ {
+ events.push_back("number_integer(val=" + std::to_string(val) + ")");
+ return true;
+ }
+
+ bool number_unsigned(number_unsigned_t val) override
+ {
+ events.push_back("number_unsigned(val=" + std::to_string(val) + ")");
+ return true;
+ }
+
+ bool number_float(number_float_t val, const string_t& s) override
+ {
+ events.push_back("number_float(val=" + std::to_string(val) + ", s=" + s + ")");
+ return true;
+ }
+
+ bool string(string_t& val) override
+ {
+ events.push_back("string(val=" + val + ")");
+ return true;
+ }
+
+ bool start_object(std::size_t elements) override
+ {
+ events.push_back("start_object(elements=" + std::to_string(elements) + ")");
+ return true;
+ }
+
+ bool end_object() override
+ {
+ events.push_back("end_object()");
+ return true;
+ }
+
+ bool start_array(std::size_t elements) override
+ {
+ events.push_back("start_array(elements=" + std::to_string(elements) + ")");
+ return true;
+ }
+
+ bool end_array() override
+ {
+ events.push_back("end_array()");
+ return true;
+ }
+
+ bool key(string_t& val) override
+ {
+ events.push_back("key(val=" + val + ")");
+ return true;
+ }
+
+ bool binary(json::binary_t& val) override
+ {
+ events.push_back("binary(val=[...])");
+ return true;
+ }
+
+ bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override
+ {
+ events.push_back("parse_error(position=" + std::to_string(position) + ", last_token=" + last_token + ",\n ex=" + std::string(ex.what()) + ")");
+ return false;
+ }
+};
+
+int main()
+{
+ // a JSON text
+ auto text = R"(
+ {
+ "Image": {
+ "Width": 800,
+ "Height": 600,
+ "Title": "View from 15th Floor",
+ "Thumbnail": {
+ "Url": "http://www.example.com/image/481989943",
+ "Height": 125,
+ "Width": 100
+ },
+ "Animated" : false,
+ "IDs": [116, 943, 234, -38793],
+ "DeletionDate": null,
+ "Distance": 12.723374634
+ }
+ }]
+ )";
+
+ // create a SAX event consumer object
+ sax_event_consumer sec;
+
+ // parse JSON
+ bool result = json::sax_parse(text, &sec);
+
+ // output the recorded events
+ for (auto& event : sec.events)
+ {
+ std::cout << event << "\n";
+ }
+
+ // output the result of sax_parse
+ std::cout << "\nresult: " << std::boolalpha << result << std::endl;
+}
+Output:
start_object(elements=18446744073709551615)
+key(val=Image)
+start_object(elements=18446744073709551615)
+key(val=Width)
+number_unsigned(val=800)
+key(val=Height)
+number_unsigned(val=600)
+key(val=Title)
+string(val=View from 15th Floor)
+key(val=Thumbnail)
+start_object(elements=18446744073709551615)
+key(val=Url)
+string(val=http://www.example.com/image/481989943)
+key(val=Height)
+number_unsigned(val=125)
+key(val=Width)
+number_unsigned(val=100)
+end_object()
+key(val=Animated)
+boolean(val=false)
+key(val=IDs)
+start_array(elements=18446744073709551615)
+number_unsigned(val=116)
+number_unsigned(val=943)
+number_unsigned(val=234)
+number_integer(val=-38793)
+end_array()
+key(val=DeletionDate)
+null()
+key(val=Distance)
+number_float(val=12.723375, s=12.723374634)
+end_object()
+end_object()
+parse_error(position=460, last_token=12.723374634<U+000A> }<U+000A> }],
+ ex=[json.exception.parse_error.101] parse error at line 17, column 6: syntax error while parsing value - unexpected ']'; expected end of input)
+
+result: false
+Some aspects of the library can be configured by defining preprocessor macros before including the json.hpp header. See also the macro overview page.
std::filesystem supportstd::ranges supportnlohmann namespace#define JSON_ASSERT(x) /* value */
+This macro controls which code is executed for runtime assertions of the library.
x (in)The default value is assert(x).
#define JSON_ASSERT(x) assert(x)
+Therefore, assertions can be switched off by defining NDEBUG.
const object). See page runtime assertions for more information.std::abort may leave the library in an undefined state.The following code will trigger an assertion at runtime:
#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ const json j = {{"key", "value"}};
+ auto v = j["missing"];
+}
+Output:
Assertion failed: (m_value.object->find(key) != m_value.object->end()), function operator[], file json.hpp, line 2144.
+The assertion reporting can be changed by defining JSON_ASSERT(x) differently.
#include <cstdio>
+#include <cstdlib>
+#define JSON_ASSERT(x) if(!(x)){fprintf(stderr, "assertion error in %s\n", __FUNCTION__); std::abort();}
+
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ const json j = {{"key", "value"}};
+ auto v = j["missing"];
+}
+Output:
assertion error in operator[]
+#define JSON_DIAGNOSTICS /* value */
+This macro enables extended diagnostics for exception messages. Possible values are 1 to enable or 0 to disable (default).
When enabled, exception messages contain a JSON Pointer to the JSON value that triggered the exception. Note that enabling this macro increases the size of every JSON value by one pointer and adds some runtime overhead.
The default value is 0 (extended diagnostics are switched off).
#define JSON_DIAGNOSTICS 0
+When the macro is not defined, the library will define it to its default value.
ABI compatibility
As of version 3.11.0, this macro is no longer required to be defined consistently throughout a codebase to avoid One Definition Rule (ODR) violations, as the value of this macro is encoded in the namespace, resulting in distinct symbol names.
This allows different parts of a codebase to use different versions or configurations of this library without causing improper behavior.
Where possible, it is still recommended that all code define this the same way for maximum interoperability.
CMake option
Diagnostic messages can also be controlled with the CMake option JSON_Diagnostics (OFF by default) which defines JSON_DIAGNOSTICS accordingly.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ json j;
+ j["address"]["street"] = "Fake Street";
+ j["address"]["housenumber"] = "12";
+
+ try
+ {
+ int housenumber = j["address"]["housenumber"];
+ }
+ catch (json::exception& e)
+ {
+ std::cout << e.what() << '\n';
+ }
+}
+Output:
[json.exception.type_error.302] type must be number, but is string
+This exception can be hard to debug if storing the value "12" and accessing it is further apart.
#include <iostream>
+
+# define JSON_DIAGNOSTICS 1
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ json j;
+ j["address"]["street"] = "Fake Street";
+ j["address"]["housenumber"] = "12";
+
+ try
+ {
+ int housenumber = j["address"]["housenumber"];
+ }
+ catch (json::exception& e)
+ {
+ std::cout << e.what() << '\n';
+ }
+}
+Output:
[json.exception.type_error.302] (/address/housenumber) type must be number, but is string
+Now the exception message contains a JSON Pointer /address/housenumber that indicates which value has the wrong type.
#define JSON_DISABLE_ENUM_SERIALIZATION /* value */
+When defined to 1, default serialization and deserialization functions for enums are excluded and have to be provided by the user, for example, using NLOHMANN_JSON_SERIALIZE_ENUM (see arbitrary type conversions for more details).
Parsing or serializing an enum will result in a compiler error.
This works for both unscoped and scoped enums.
The default value is 0.
#define JSON_DISABLE_ENUM_SERIALIZATION 0
+CMake option
Enum serialization can also be controlled with the CMake option JSON_DisableEnumSerialization (OFF by default) which defines JSON_DISABLE_ENUM_SERIALIZATION accordingly.
The code below forces the library not to create default serialization/deserialization functions from_json and to_json, meaning the code below does not compile.
#define JSON_DISABLE_ENUM_SERIALIZATION 1
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+enum class Choice
+{
+ first,
+ second,
+};
+
+int main()
+{
+ // normally invokes to_json serialization function but with JSON_DISABLE_ENUM_SERIALIZATION defined, it does not
+ const json j = Choice::first;
+
+ // normally invokes from_json parse function but with JSON_DISABLE_ENUM_SERIALIZATION defined, it does not
+ Choice ch = j.get<Choice>();
+}
+The code below forces the library not to create default serialization/deserialization functions from_json and to_json, but uses NLOHMANN_JSON_SERIALIZE_ENUM to parse and serialize the enum.
#define JSON_DISABLE_ENUM_SERIALIZATION 1
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+enum class Choice
+{
+ first,
+ second,
+};
+
+NLOHMANN_JSON_SERIALIZE_ENUM(Choice,
+{
+ { Choice::first, "first" },
+ { Choice::second, "second" },
+})
+
+int main()
+{
+ // uses user-defined to_json function defined by macro
+ const json j = Choice::first;
+
+ // uses user-defined from_json function defined by macro
+ Choice ch = j.get<Choice>();
+}
+The code below forces the library not to create default serialization/deserialization functions from_json and to_json, but uses user-defined functions to parse and serialize the enum.
#define JSON_DISABLE_ENUM_SERIALIZATION 1
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+enum class Choice
+{
+ first,
+ second,
+};
+
+void from_json(const json& j, Choice& ch)
+{
+ auto value = j.get<std::string>();
+ if (value == "first")
+ {
+ ch = Choice::first;
+ }
+ else if (value == "second")
+ {
+ ch = Choice::second;
+ }
+}
+
+void to_json(json& j, const Choice& ch)
+{
+ auto value = j.get<std::string>();
+ if (value == "first")
+ {
+ ch = Choice::first;
+ }
+ else if (value == "second")
+ {
+ ch = Choice::second;
+ }
+}
+
+int main()
+{
+ // uses user-defined to_json function
+ const json j = Choice::first;
+
+ // uses user-defined from_json function
+ Choice ch = j.get<Choice>();
+}
+#define JSON_HAS_CPP_11
+#define JSON_HAS_CPP_14
+#define JSON_HAS_CPP_17
+#define JSON_HAS_CPP_20
+The library targets C++11, but also supports some features introduced in later C++ versions (e.g., std::string_view support for C++17). For these new features, the library implements some preprocessor checks to determine the C++ standard. By defining any of these symbols, the internal check is overridden and the provided C++ version is unconditionally assumed. This can be helpful for compilers that only implement parts of the standard and would be detected incorrectly.
The default value is detected based on preprocessor macros such as __cplusplus, _HAS_CXX17, or _MSVC_LANG.
JSON_HAS_CPP_11 is always defined.The code below forces the library to use the C++14 standard:
#define JSON_HAS_CPP_14 1
+#include <nlohmann/json.hpp>
+
+...
+#define JSON_HAS_FILESYSTEM /* value */
+#define JSON_HAS_EXPERIMENTAL_FILESYSTEM /* value */
+When compiling with C++17, the library provides conversions from and to std::filesystem::path. As compiler support for filesystem is limited, the library tries to detect whether <filesystem>/std::filesystem (JSON_HAS_FILESYSTEM) or <experimental/filesystem>/std::experimental::filesystem (JSON_HAS_EXPERIMENTAL_FILESYSTEM) should be used. To override the built-in check, define JSON_HAS_FILESYSTEM or JSON_HAS_EXPERIMENTAL_FILESYSTEM to 1.
The default value is detected based on the preprocessor macros __cpp_lib_filesystem, __cpp_lib_experimental_filesystem, __has_include(<filesystem>), or __has_include(<experimental/filesystem>).
stdc++fs to be linked to for filesystem support.The code below forces the library to use the header <experimental/filesystem>.
#define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1
+#include <nlohmann/json.hpp>
+
+...
+#define JSON_HAS_RANGES /* value */
+This macro indicates whether the standard library has any support for ranges. Implies support for concepts. Possible values are 1 when supported or 0 when unsupported.
The default value is detected based on the preprocessor macro __cpp_lib_ranges.
When the macro is not defined, the library will define it to its default value.
The code below forces the library to enable support for ranges:
#define JSON_HAS_RANGES 1
+#include <nlohmann/json.hpp>
+
+...
+#define JSON_HAS_THREE_WAY_COMPARISON /* value */
+This macro indicates whether the compiler and standard library support 3-way comparison. Possible values are 1 when supported or 0 when unsupported.
The default value is detected based on the preprocessor macros __cpp_impl_three_way_comparison and __cpp_lib_three_way_comparison.
When the macro is not defined, the library will define it to its default value.
The code below forces the library to use 3-way comparison:
#define JSON_HAS_THREE_WAY_COMPARISON 1
+#include <nlohmann/json.hpp>
+
+...
+#define JSON_NO_IO
+When defined, headers <cstdio>, <ios>, <iosfwd>, <istream>, and <ostream> are not included and parse functions relying on these headers are excluded. This is relevant for environments where these I/O functions are disallowed for security reasons (e.g., Intel Software Guard Extensions (SGX)).
By default, JSON_NO_IO is not defined.
#undef JSON_NO_IO
+The code below forces the library not to use the headers <cstdio>, <ios>, <iosfwd>, <istream>, and <ostream>.
#define JSON_NO_IO 1
+#include <nlohmann/json.hpp>
+
+...
+#define JSON_NOEXCEPTION
+Exceptions can be switched off by defining the symbol JSON_NOEXCEPTION. When defining JSON_NOEXCEPTION, try is replaced by if (true), catch is replaced by if (false), and throw is replaced by std::abort().
The same effect is achieved by setting the compiler flag -fno-exceptions.
By default, the macro is not defined.
#undef JSON_NOEXCEPTION
+The explanatory what() string of exceptions is not available for MSVC if exceptions are disabled, see #2824.
The code below switches off exceptions in the library.
#define JSON_NOEXCEPTION 1
+#include <nlohmann/json.hpp>
+
+...
+Added in version 2.1.0.
#define JSON_SKIP_LIBRARY_VERSION_CHECK
+When defined, the library will not create a compiler warning when a different version of the library was already included.
By default, the macro is not defined.
#undef JSON_SKIP_LIBRARY_VERSION_CHECK
+ABI compatibility
Mixing different library versions in the same code can be a problem as the different versions may not be ABI compatible.
Example
The following warning will be shown in case a different version of the library was already included:
Already included a different version of the library!
+Added in version 3.11.0.
#define JSON_SKIP_UNSUPPORTED_COMPILER_CHECK
+When defined, the library will not create a compile error when a known unsupported compiler is detected. This allows to use the library with compilers that do not fully support C++11 and may only work if unsupported features are not used.
By default, the macro is not defined.
#undef JSON_SKIP_UNSUPPORTED_COMPILER_CHECK
+The code below switches off the check whether the compiler is supported.
#define JSON_SKIP_UNSUPPORTED_COMPILER_CHECK 1
+#include <nlohmann/json.hpp>
+
+...
+Added in version 3.2.0.
// (1)
+#define JSON_CATCH_USER(exception) /* value */
+// (2)
+#define JSON_THROW_USER(exception) /* value */
+// (3)
+#define JSON_TRY_USER /* value */
+Controls how exceptions are handled by the library.
catch calls inside the library. The argument is the type of the exception to catch. As of version 3.8.0, the library only catches std::out_of_range exceptions internally to rethrow them as json::out_of_range exceptions. The macro is always followed by a scope.throw calls inside the library. The argument is the exception to be thrown. Note that JSON_THROW_USER should leave the current scope (e.g., by throwing or aborting), as continuing after it may yield undefined behavior.try calls inside the library. It has no arguments and is always followed by a scope.exception (in)By default, the macros map to their respective C++ keywords:
#define JSON_CATCH_USER(exception) catch(exception)
+#define JSON_THROW_USER(exception) throw exception
+#define JSON_TRY_USER try
+When exceptions are switched off, the try block is executed unconditionally, and throwing exceptions is replaced by calling std::abort to make reaching the throw branch abort the process.
#define JSON_THROW_USER(exception) std::abort()
+#define JSON_TRY_USER if (true)
+#define JSON_CATCH_USER(exception) if (false)
+The code below switches off exceptions and creates a log entry with a detailed error message in case of errors.
#include <iostream>
+
+#define JSON_TRY_USER if(true)
+#define JSON_CATCH_USER(exception) if(false)
+#define JSON_THROW_USER(exception) \
+ {std::clog << "Error in " << __FILE__ << ":" << __LINE__ \
+ << " (function " << __FUNCTION__ << ") - " \
+ << (exception).what() << std::endl; \
+ std::abort();}
+
+#include <nlohmann/json.hpp>
+#define JSON_USE_GLOBAL_UDLS /* value */
+When defined to 1, the user-defined string literals (UDLs) are placed into the global namespace instead of nlohmann::literals::json_literals.
The default value is 1.
#define JSON_USE_GLOBAL_UDLS 1
+When the macro is not defined, the library will define it to its default value.
Future behavior change
The user-defined string literals will be removed from the global namespace in the next major release of the library.
To prepare existing code, define JSON_USE_GLOBAL_UDLS to 0 and bring the string literals into scope where needed. Refer to any of the string literals for details.
CMake option
The placement of user-defined string literals can also be controlled with the CMake option JSON_GlobalUDLs (ON by default) which defines JSON_USE_GLOBAL_UDLS accordingly.
The code below shows the default behavior using the _json UDL.
#include <nlohmann/json.hpp>
+
+#include <iostream>
+
+int main()
+{
+ auto j = "42"_json;
+
+ std::cout << j << std::endl;
+}
+Output:
42
+The code below shows how UDLs need to be brought into scope before using _json when JSON_USE_GLOBAL_UDLS is defined to 0.
#define JSON_USE_GLOBAL_UDLS 0
+#include <nlohmann/json.hpp>
+
+#include <iostream>
+
+int main()
+{
+ // auto j = "42"_json; // This line would fail to compile,
+ // because the UDLs are not in the global namespace
+
+ // Bring the UDLs into scope
+ using namespace nlohmann::json_literals;
+
+ auto j = "42"_json;
+
+ std::cout << j << std::endl;
+}
+Output:
42
+#define JSON_USE_IMPLICIT_CONVERSIONS /* value */
+When defined to 0, implicit conversions are switched off. By default, implicit conversions are switched on. The value directly affects operator ValueType.
By default, implicit conversions are enabled.
#define JSON_USE_IMPLICIT_CONVERSIONS 1
+Future behavior change
Implicit conversions will be switched off by default in the next major release of the library.
You can prepare existing code by already defining JSON_USE_IMPLICIT_CONVERSIONS to 0 and replace any implicit conversions with calls to get.
CMake option
Implicit conversions can also be controlled with the CMake option JSON_ImplicitConversions (ON by default) which defines JSON_USE_IMPLICIT_CONVERSIONS accordingly.
This is an example for an implicit conversion:
json j = "Hello, world!";
+std::string s = j;
+When JSON_USE_IMPLICIT_CONVERSIONS is defined to 0, the code above does no longer compile. Instead, it must be written like this:
json j = "Hello, world!";
+auto s = j.get<std::string>();
+#define JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON /* value */
+This macro enables the (incorrect) legacy comparison behavior of discarded JSON values. Possible values are 1 to enable or 0 to disable (default).
When enabled, comparisons involving at least one discarded JSON value yield results as follows:
| Operator | Result |
|---|---|
== | false |
!= | true |
< | false |
<= | true |
>= | true |
> | false |
Otherwise, comparisons involving at least one discarded JSON value always yield false.
The default value is 0.
#define JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON 0
+When the macro is not defined, the library will define it to its default value.
Inconsistent behavior in C++20 and beyond
When targeting C++20 or above, enabling the legacy comparison behavior is strongly discouraged.
<=>) will always give the correct result (std::partial_ordering::unordered) regardless of the value of JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON.Code outside your control may use either 3-way comparison or the equality and relational operators, resulting in inconsistent and unpredictable behavior.
See operator<=> for more information on 3-way comparison.
Deprecation
The legacy comparison behavior is deprecated and may be removed in a future major version release.
New code should not depend on it and existing code should try to remove or rewrite expressions relying on it.
CMake option
Legacy comparison can also be controlled with the CMake option JSON_LegacyDiscardedValueComparison (OFF by default) which defines JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON accordingly.
The code below switches on the legacy discarded value comparison behavior in the library.
#define JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON 1
+#include <nlohmann/json.hpp>
+
+...
+#define NLOHMANN_DEFINE_TYPE_INTRUSIVE(type, member...) // (1)
+#define NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(type, member...) // (2)
+These macros can be used to simplify the serialization/deserialization of types if you want to use a JSON object as serialization and want to use the member variable names as object keys in that object. The macro is to be defined inside the class/struct to create code for. Unlike NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE, it can access private members. The first parameter is the name of the class/struct, and all remaining parameters name the members.
at during deserialization and will throw out_of_range.403 if a key is missing in the JSON object.value during deserialization and fall back to the default value for the respective type of the member variable if a key in the JSON object is missing. The generated from_json() function default constructs an object and uses its values as the defaults when calling the value function.type (in)member (in)The macros add two friend functions to the class which take care of the serialization and deserialization:
friend void to_json(nlohmann::json&, const type&);
+friend void from_json(const nlohmann::json&, type&);
+See examples below for the concrete generated code.
Prerequisites
type must be default constructible. See How can I use get() for non-default constructible/non-copyable types? for how to overcome this limitation.Implementation limits
to_json/from_json functions manually.nlohmann::json type; other specializations such as nlohmann::ordered_json are currently unsupported.Consider the following complete example:
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+using namespace nlohmann::literals;
+
+namespace ns
+{
+class person
+{
+ private:
+ std::string name = "John Doe";
+ std::string address = "123 Fake St";
+ int age = -1;
+
+ public:
+ person() = default;
+ person(std::string name_, std::string address_, int age_)
+ : name(std::move(name_)), address(std::move(address_)), age(age_)
+ {}
+
+ NLOHMANN_DEFINE_TYPE_INTRUSIVE(person, name, address, age)
+};
+} // namespace ns
+
+int main()
+{
+ ns::person p = {"Ned Flanders", "744 Evergreen Terrace", 60};
+
+ // serialization: person -> json
+ json j = p;
+ std::cout << "serialization: " << j << std::endl;
+
+ // deserialization: json -> person
+ json j2 = R"({"address": "742 Evergreen Terrace", "age": 40, "name": "Homer Simpson"})"_json;
+ auto p2 = j2.get<ns::person>();
+
+ // incomplete deserialization:
+ json j3 = R"({"address": "742 Evergreen Terrace", "name": "Maggie Simpson"})"_json;
+ try
+ {
+ auto p3 = j3.get<ns::person>();
+ }
+ catch (json::exception& e)
+ {
+ std::cout << "deserialization failed: " << e.what() << std::endl;
+ }
+}
+Output:
serialization: {"address":"744 Evergreen Terrace","age":60,"name":"Ned Flanders"}
+deserialization failed: [json.exception.out_of_range.403] key 'age' not found
+Notes:
ns::person is default-constructible. This is a requirement for using the macro.ns::person has private member variables. This makes NLOHMANN_DEFINE_TYPE_INTRUSIVE applicable, but not NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE.NLOHMANN_DEFINE_TYPE_INTRUSIVE is used inside the class.NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT can be used.The macro is equivalent to:
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+using namespace nlohmann::literals;
+
+namespace ns
+{
+class person
+{
+ private:
+ std::string name = "John Doe";
+ std::string address = "123 Fake St";
+ int age = -1;
+
+ public:
+ person() = default;
+ person(std::string name_, std::string address_, int age_)
+ : name(std::move(name_)), address(std::move(address_)), age(age_)
+ {}
+
+ friend void to_json(nlohmann::json& nlohmann_json_j, const person& nlohmann_json_t)
+ {
+ nlohmann_json_j["name"] = nlohmann_json_t.name;
+ nlohmann_json_j["address"] = nlohmann_json_t.address;
+ nlohmann_json_j["age"] = nlohmann_json_t.age;
+ }
+
+ friend void from_json(const nlohmann::json& nlohmann_json_j, person& nlohmann_json_t)
+ {
+ nlohmann_json_t.name = nlohmann_json_j.at("name");
+ nlohmann_json_t.address = nlohmann_json_j.at("address");
+ nlohmann_json_t.age = nlohmann_json_j.at("age");
+ }
+};
+} // namespace ns
+
+int main()
+{
+ ns::person p = {"Ned Flanders", "744 Evergreen Terrace", 60};
+
+ // serialization: person -> json
+ json j = p;
+ std::cout << "serialization: " << j << std::endl;
+
+ // deserialization: json -> person
+ json j2 = R"({"address": "742 Evergreen Terrace", "age": 40, "name": "Homer Simpson"})"_json;
+ auto p2 = j2.get<ns::person>();
+
+ // incomplete deserialization:
+ json j3 = R"({"address": "742 Evergreen Terrace", "name": "Maggie Simpson"})"_json;
+ try
+ {
+ auto p3 = j3.get<ns::person>();
+ }
+ catch (json::exception& e)
+ {
+ std::cout << "deserialization failed: " << e.what() << std::endl;
+ }
+}
+Consider the following complete example:
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+using namespace nlohmann::literals;
+
+namespace ns
+{
+class person
+{
+ private:
+ std::string name = "John Doe";
+ std::string address = "123 Fake St";
+ int age = -1;
+
+ public:
+ person() = default;
+ person(std::string name_, std::string address_, int age_)
+ : name(std::move(name_)), address(std::move(address_)), age(age_)
+ {}
+
+ NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(person, name, address, age)
+};
+} // namespace ns
+
+int main()
+{
+ ns::person p = {"Ned Flanders", "744 Evergreen Terrace", 60};
+
+ // serialization: person -> json
+ json j = p;
+ std::cout << "serialization: " << j << std::endl;
+
+ // deserialization: json -> person
+ json j2 = R"({"address": "742 Evergreen Terrace", "age": 40, "name": "Homer Simpson"})"_json;
+ auto p2 = j2.get<ns::person>();
+
+ // incomplete deserialization:
+ json j3 = R"({"address": "742 Evergreen Terrace", "name": "Maggie Simpson"})"_json;
+ auto p3 = j3.get<ns::person>();
+ std::cout << "roundtrip: " << json(p3) << std::endl;
+}
+Output:
serialization: {"address":"744 Evergreen Terrace","age":60,"name":"Ned Flanders"}
+roundtrip: {"address":"742 Evergreen Terrace","age":-1,"name":"Maggie Simpson"}
+Notes:
ns::person is default-constructible. This is a requirement for using the macro.ns::person has private member variables. This makes NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT applicable, but not NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT.NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT is used inside the class.-1 is used.The macro is equivalent to:
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+using namespace nlohmann::literals;
+
+namespace ns
+{
+class person
+{
+ private:
+ std::string name = "John Doe";
+ std::string address = "123 Fake St";
+ int age = -1;
+
+ public:
+ person() = default;
+ person(std::string name_, std::string address_, int age_)
+ : name(std::move(name_)), address(std::move(address_)), age(age_)
+ {}
+
+ friend void to_json(nlohmann::json& nlohmann_json_j, const person& nlohmann_json_t)
+ {
+ nlohmann_json_j["name"] = nlohmann_json_t.name;
+ nlohmann_json_j["address"] = nlohmann_json_t.address;
+ nlohmann_json_j["age"] = nlohmann_json_t.age;
+ }
+
+ friend void from_json(const nlohmann::json& nlohmann_json_j, person& nlohmann_json_t)
+ {
+ person nlohmann_json_default_obj;
+ nlohmann_json_t.name = nlohmann_json_j.value("name", nlohmann_json_default_obj.name);
+ nlohmann_json_t.address = nlohmann_json_j.value("address", nlohmann_json_default_obj.address);
+ nlohmann_json_t.age = nlohmann_json_j.value("age", nlohmann_json_default_obj.age);
+ }
+};
+} // namespace ns
+
+int main()
+{
+ ns::person p = {"Ned Flanders", "744 Evergreen Terrace", 60};
+
+ // serialization: person -> json
+ json j = p;
+ std::cout << "serialization: " << j << std::endl;
+
+ // deserialization: json -> person
+ json j2 = R"({"address": "742 Evergreen Terrace", "age": 40, "name": "Homer Simpson"})"_json;
+ auto p2 = j2.get<ns::person>();
+
+ // incomplete deserialization:
+ json j3 = R"({"address": "742 Evergreen Terrace", "name": "Maggie Simpson"})"_json;
+ auto p3 = j3.get<ns::person>();
+ std::cout << "roundtrip: " << json(p3) << std::endl;
+}
+Note how a default-initialized person object is used in the from_json to fill missing values.
#define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(type, member...) // (1)
+#define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT(type, member...) // (2)
+These macros can be used to simplify the serialization/deserialization of types if you want to use a JSON object as serialization and want to use the member variable names as object keys in that object. The macro is to be defined outside the class/struct to create code for, but inside its namespace. Unlike NLOHMANN_DEFINE_TYPE_INTRUSIVE, it cannot access private members. The first parameter is the name of the class/struct, and all remaining parameters name the members.
at during deserialization and will throw out_of_range.403 if a key is missing in the JSON object.value during deserialization and fall back to the default value for the respective type of the member variable if a key in the JSON object is missing. The generated from_json() function default constructs an object and uses its values as the defaults when calling the value function.type (in)member (in)The macros add two functions to the namespace which take care of the serialization and deserialization:
void to_json(nlohmann::json&, const type&);
+void from_json(const nlohmann::json&, type&);
+See examples below for the concrete generated code.
Prerequisites
type must be default constructible. See How can I use get() for non-default constructible/non-copyable types? for how to overcome this limitation.Implementation limits
to_json/from_json functions manually.nlohmann::json type; other specializations such as nlohmann::ordered_json are currently unsupported.Consider the following complete example:
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+using namespace nlohmann::literals;
+
+namespace ns
+{
+struct person
+{
+ std::string name;
+ std::string address;
+ int age;
+};
+
+NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(person, name, address, age)
+} // namespace ns
+
+int main()
+{
+ ns::person p = {"Ned Flanders", "744 Evergreen Terrace", 60};
+
+ // serialization: person -> json
+ json j = p;
+ std::cout << "serialization: " << j << std::endl;
+
+ // deserialization: json -> person
+ json j2 = R"({"address": "742 Evergreen Terrace", "age": 40, "name": "Homer Simpson"})"_json;
+ auto p2 = j2.get<ns::person>();
+
+ // incomplete deserialization:
+ json j3 = R"({"address": "742 Evergreen Terrace", "name": "Maggie Simpson"})"_json;
+ try
+ {
+ auto p3 = j3.get<ns::person>();
+ }
+ catch (json::exception& e)
+ {
+ std::cout << "deserialization failed: " << e.what() << std::endl;
+ }
+}
+Output:
serialization: {"address":"744 Evergreen Terrace","age":60,"name":"Ned Flanders"}
+deserialization failed: [json.exception.out_of_range.403] key 'age' not found
+Notes:
ns::person is default-constructible. This is a requirement for using the macro.ns::person has only public member variables. This makes NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE applicable.NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE is used outside the class, but inside its namespace ns.NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT can be used.The macro is equivalent to:
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+using namespace nlohmann::literals;
+
+namespace ns
+{
+struct person
+{
+ std::string name;
+ std::string address;
+ int age;
+};
+
+void to_json(nlohmann::json& nlohmann_json_j, const person& nlohmann_json_t)
+{
+ nlohmann_json_j["name"] = nlohmann_json_t.name;
+ nlohmann_json_j["address"] = nlohmann_json_t.address;
+ nlohmann_json_j["age"] = nlohmann_json_t.age;
+}
+
+void from_json(const nlohmann::json& nlohmann_json_j, person& nlohmann_json_t)
+{
+ nlohmann_json_t.name = nlohmann_json_j.at("name");
+ nlohmann_json_t.address = nlohmann_json_j.at("address");
+ nlohmann_json_t.age = nlohmann_json_j.at("age");
+}
+} // namespace ns
+
+int main()
+{
+ ns::person p = {"Ned Flanders", "744 Evergreen Terrace", 60};
+
+ // serialization: person -> json
+ json j = p;
+ std::cout << "serialization: " << j << std::endl;
+
+ // deserialization: json -> person
+ json j2 = R"({"address": "742 Evergreen Terrace", "age": 40, "name": "Homer Simpson"})"_json;
+ auto p2 = j2.get<ns::person>();
+
+ // incomplete deserialization:
+ json j3 = R"({"address": "742 Evergreen Terrace", "name": "Maggie Simpson"})"_json;
+ try
+ {
+ auto p3 = j3.get<ns::person>();
+ }
+ catch (json::exception& e)
+ {
+ std::cout << "deserialization failed: " << e.what() << std::endl;
+ }
+}
+Consider the following complete example:
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+using namespace nlohmann::literals;
+
+namespace ns
+{
+struct person
+{
+ std::string name = "John Doe";
+ std::string address = "123 Fake St";
+ int age = -1;
+
+ person() = default;
+ person(std::string name_, std::string address_, int age_)
+ : name(std::move(name_)), address(std::move(address_)), age(age_)
+ {}
+};
+
+NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT(person, name, address, age)
+} // namespace ns
+
+int main()
+{
+ ns::person p = {"Ned Flanders", "744 Evergreen Terrace", 60};
+
+ // serialization: person -> json
+ json j = p;
+ std::cout << "serialization: " << j << std::endl;
+
+ // deserialization: json -> person
+ json j2 = R"({"address": "742 Evergreen Terrace", "age": 40, "name": "Homer Simpson"})"_json;
+ auto p2 = j2.get<ns::person>();
+
+ // incomplete deserialization:
+ json j3 = R"({"address": "742 Evergreen Terrace", "name": "Maggie Simpson"})"_json;
+ auto p3 = j3.get<ns::person>();
+ std::cout << "roundtrip: " << json(p3) << std::endl;
+}
+Output:
serialization: {"address":"744 Evergreen Terrace","age":60,"name":"Ned Flanders"}
+roundtrip: {"address":"742 Evergreen Terrace","age":-1,"name":"Maggie Simpson"}
+Notes:
ns::person is default-constructible. This is a requirement for using the macro.ns::person has only public member variables. This makes NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT applicable.NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT is used outside the class, but inside its namespace ns.-1 is used.The macro is equivalent to:
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+using namespace nlohmann::literals;
+
+namespace ns
+{
+struct person
+{
+ std::string name = "John Doe";
+ std::string address = "123 Fake St";
+ int age = -1;
+
+ person() = default;
+ person(std::string name_, std::string address_, int age_)
+ : name(std::move(name_)), address(std::move(address_)), age(age_)
+ {}
+};
+
+void to_json(nlohmann::json& nlohmann_json_j, const person& nlohmann_json_t)
+{
+ nlohmann_json_j["name"] = nlohmann_json_t.name;
+ nlohmann_json_j["address"] = nlohmann_json_t.address;
+ nlohmann_json_j["age"] = nlohmann_json_t.age;
+}
+
+void from_json(const nlohmann::json& nlohmann_json_j, person& nlohmann_json_t)
+{
+ person nlohmann_json_default_obj;
+ nlohmann_json_t.name = nlohmann_json_j.value("name", nlohmann_json_default_obj.name);
+ nlohmann_json_t.address = nlohmann_json_j.value("address", nlohmann_json_default_obj.address);
+ nlohmann_json_t.age = nlohmann_json_j.value("age", nlohmann_json_default_obj.age);
+}
+} // namespace ns
+
+int main()
+{
+ ns::person p = {"Ned Flanders", "744 Evergreen Terrace", 60};
+
+ // serialization: person -> json
+ json j = p;
+ std::cout << "serialization: " << j << std::endl;
+
+ // deserialization: json -> person
+ json j2 = R"({"address": "742 Evergreen Terrace", "age": 40, "name": "Homer Simpson"})"_json;
+ auto p2 = j2.get<ns::person>();
+
+ // incomplete deserialization:
+ json j3 = R"({"address": "742 Evergreen Terrace", "name": "Maggie Simpson"})"_json;
+ auto p3 = j3.get<ns::person>();
+ std::cout << "roundtrip: " << json(p3) << std::endl;
+}
+Note how a default-initialized person object is used in the from_json to fill missing values.
#define NLOHMANN_JSON_NAMESPACE /* value */
+This macro evaluates to the full name of the nlohmann namespace.
The default value consists of the root namespace (nlohmann) and an inline ABI namespace. See nlohmann Namespace for details.
When the macro is not defined, the library will define it to its default value. Overriding this value has no effect on the library.
The example shows how to use NLOHMANN_JSON_NAMESPACE instead of just nlohmann, as well as how to output the value of NLOHMANN_JSON_NAMESPACE.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+// possible use case: use NLOHMANN_JSON_NAMESPACE instead of nlohmann
+using json = NLOHMANN_JSON_NAMESPACE::json;
+
+// macro needed to output the NLOHMANN_JSON_NAMESPACE as string literal
+#define Q(x) #x
+#define QUOTE(x) Q(x)
+
+int main()
+{
+ std::cout << QUOTE(NLOHMANN_JSON_NAMESPACE) << std::endl;
+}
+Output:
nlohmann::json_abi_v3_11_2
+#define NLOHMANN_JSON_NAMESPACE_BEGIN /* value */ // (1)
+#define NLOHMANN_JSON_NAMESPACE_END /* value */ // (2)
+These macros can be used to open and close the nlohmann namespace. See nlohmann Namespace for details.
The default definitions open and close the nlohmann namespace. The precise definition of [NLOHMANN_JSON_NAMESPACE_BEGIN] varies as described here.
Default definition of NLOHMANN_JSON_NAMESPACE_BEGIN:
namespace nlohmann
+{
+inline namespace json_abi_v3_11_2
+{
+Default definition of NLOHMANN_JSON_NAMESPACE_END:
} // namespace json_abi_v3_11_2
+} // namespace nlohmann
+When these macros are not defined, the library will define them to their default definitions.
The example shows how to use NLOHMANN_JSON_NAMESPACE_BEGIN/NLOHMANN_JSON_NAMESPACE_END from the How do I convert third-party types? page.
#include <iostream>
+#include <optional>
+#include <nlohmann/json.hpp>
+
+// partial specialization (see https://json.nlohmann.me/features/arbitrary_types/)
+NLOHMANN_JSON_NAMESPACE_BEGIN
+template <typename T>
+struct adl_serializer<std::optional<T>>
+{
+ static void to_json(json& j, const std::optional<T>& opt)
+ {
+ if (opt == std::nullopt)
+ {
+ j = nullptr;
+ }
+ else
+ {
+ j = *opt;
+ }
+ }
+};
+NLOHMANN_JSON_NAMESPACE_END
+
+int main()
+{
+ std::optional<int> o1 = 1;
+ std::optional<int> o2 = std::nullopt;
+
+ NLOHMANN_JSON_NAMESPACE::json j;
+ j.push_back(o1);
+ j.push_back(o2);
+ std::cout << j << std::endl;
+}
+Output:
[1,null]
+#define NLOHMANN_JSON_NAMESPACE_NO_VERSION /* value */
+If defined to 1, the version component is omitted from the inline namespace. See nlohmann Namespace for details.
The default value is 0.
#define NLOHMANN_JSON_NAMESPACE_NO_VERSION 0
+When the macro is not defined, the library will define it to its default value.
The example shows how to use NLOHMANN_JSON_NAMESPACE_NO_VERSION to disable the version component of the inline namespace.
#include <iostream>
+
+#define NLOHMANN_JSON_NAMESPACE_NO_VERSION 1
+#include <nlohmann/json.hpp>
+
+// macro needed to output the NLOHMANN_JSON_NAMESPACE as string literal
+#define Q(x) #x
+#define QUOTE(x) Q(x)
+
+int main()
+{
+ std::cout << QUOTE(NLOHMANN_JSON_NAMESPACE) << std::endl;
+}
+Output:
nlohmann::json_abi
+nlohmann NamespaceNLOHMANN_JSON_NAMESPACENLOHMANN_JSON_NAMESPACE_BEGIN, NLOHMANN_JSON_NAMESPACE_END#define NLOHMANN_JSON_SERIALIZE_ENUM(type, conversion...)
+By default, enum values are serialized to JSON as integers. In some cases this could result in undesired behavior. If an enum is modified or re-ordered after data has been serialized to JSON, the later de-serialized JSON data may be undefined or a different enum value than was originally intended.
The NLOHMANN_JSON_SERIALIZE_ENUM allows to define a user-defined serialization for every enumerator.
type (in)conversion (in)The macros add two friend functions to the class which take care of the serialization and deserialization:
template<typename BasicJsonType>
+inline void to_json(BasicJsonType& j, const type& e);
+template<typename BasicJsonType>
+inline void from_json(const BasicJsonType& j, type& e);
+Prerequisites
The macro must be used inside the namespace of the enum.
Important notes
get<ENUM_TYPE>(), undefined JSON values will default to the first specified conversion. Select this default pair carefully. See example 1 below.The example shows how NLOHMANN_JSON_SERIALIZE_ENUM can be used to serialize/deserialize both classical enums and C++11 enum classes:
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+namespace ns
+{
+enum TaskState
+{
+ TS_STOPPED,
+ TS_RUNNING,
+ TS_COMPLETED,
+ TS_INVALID = -1
+};
+
+NLOHMANN_JSON_SERIALIZE_ENUM(TaskState,
+{
+ { TS_INVALID, nullptr },
+ { TS_STOPPED, "stopped" },
+ { TS_RUNNING, "running" },
+ { TS_COMPLETED, "completed" }
+})
+
+enum class Color
+{
+ red, green, blue, unknown
+};
+
+NLOHMANN_JSON_SERIALIZE_ENUM(Color,
+{
+ { Color::unknown, "unknown" }, { Color::red, "red" },
+ { Color::green, "green" }, { Color::blue, "blue" }
+})
+} // namespace ns
+
+int main()
+{
+ // serialization
+ json j_stopped = ns::TS_STOPPED;
+ json j_red = ns::Color::red;
+ std::cout << "ns::TS_STOPPED -> " << j_stopped
+ << ", ns::Color::red -> " << j_red << std::endl;
+
+ // deserialization
+ json j_running = "running";
+ json j_blue = "blue";
+ auto running = j_running.get<ns::TaskState>();
+ auto blue = j_blue.get<ns::Color>();
+ std::cout << j_running << " -> " << running
+ << ", " << j_blue << " -> " << static_cast<int>(blue) << std::endl;
+
+ // deserializing undefined JSON value to enum
+ // (where the first map entry above is the default)
+ json j_pi = 3.14;
+ auto invalid = j_pi.get<ns::TaskState>();
+ auto unknown = j_pi.get<ns::Color>();
+ std::cout << j_pi << " -> " << invalid << ", "
+ << j_pi << " -> " << static_cast<int>(unknown) << std::endl;
+}
+Output:
ns::TS_STOPPED -> "stopped", ns::Color::red -> "red"
+"running" -> 1, "blue" -> 2
+3.14 -> -1, 3.14 -> 3
+The example shows how to use multiple conversions for a single enumerator. In the example, Color::red will always be serialized to "red", because the first occurring conversion. The second conversion, however, offers an alternative deserialization from "rot" to Color::red.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+namespace ns
+{
+enum class Color
+{
+ red, green, blue, unknown
+};
+
+NLOHMANN_JSON_SERIALIZE_ENUM(Color,
+{
+ { Color::unknown, "unknown" }, { Color::red, "red" },
+ { Color::green, "green" }, { Color::blue, "blue" },
+ { Color::red, "rot" } // a second conversion for Color::red
+})
+}
+
+int main()
+{
+ // serialization
+ json j_red = ns::Color::red;
+ std::cout << static_cast<int>(ns::Color::red) << " -> " << j_red << std::endl;
+
+ // deserialization
+ json j_rot = "rot";
+ auto rot = j_rot.get<ns::Color>();
+ auto red = j_red.get<ns::Color>();
+ std::cout << j_rot << " -> " << static_cast<int>(rot) << std::endl;
+ std::cout << j_red << " -> " << static_cast<int>(red) << std::endl;
+}
+Output:
0 -> "red"
+"rot" -> 0
+"red" -> 0
+Added in version 3.4.0.
#define NLOHMANN_JSON_VERSION_MAJOR /* value */
+#define NLOHMANN_JSON_VERSION_MINOR /* value */
+#define NLOHMANN_JSON_VERSION_PATCH /* value */
+These macros are defined by the library and contain the version numbers according to Semantic Versioning 2.0.0.
The macros are defined according to the current library version.
The example below shows how NLOHMANN_JSON_VERSION_MAJOR, NLOHMANN_JSON_VERSION_MINOR, and NLOHMANN_JSON_VERSION_PATCH are defined by the library.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ std::cout << "JSON for Modern C++ version "
+ << NLOHMANN_JSON_VERSION_MAJOR << "."
+ << NLOHMANN_JSON_VERSION_MINOR << "."
+ << NLOHMANN_JSON_VERSION_PATCH << std::endl;
+}
+Output:
JSON for Modern C++ version 3.11.2
+std::istream& operator>>(std::istream& i, basic_json& j);
+Deserializes an input stream to a JSON value.
i (in, out)j (in, out)the stream i
parse_error.101 in case of an unexpected token.parse_error.102 if to_unicode fails or surrogate error.parse_error.103 if to_unicode fails.Linear in the length of the input. The parser is a predictive LL(1) parser.
A UTF-8 byte order mark is silently ignored.
Deprecation
This function replaces function std::istream& operator<<(basic_json& j, std::istream& i) which has been deprecated in version 3.0.0. It will be removed in version 4.0.0. Please replace calls like j << i; with i >> j;.
The example below shows how a JSON value is constructed by reading a serialization from a stream.
#include <iostream>
+#include <iomanip>
+#include <sstream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create stream with serialized JSON
+ std::stringstream ss;
+ ss << R"({
+ "number": 23,
+ "string": "Hello, world!",
+ "array": [1, 2, 3, 4, 5],
+ "boolean": false,
+ "null": null
+ })";
+
+ // create JSON value and read the serialization from the stream
+ json j;
+ ss >> j;
+
+ // serialize JSON
+ std::cout << std::setw(2) << j << '\n';
+}
+Output:
{
+ "array": [
+ 1,
+ 2,
+ 3,
+ 4,
+ 5
+ ],
+ "boolean": false,
+ "null": null,
+ "number": 23,
+ "string": "Hello, world!"
+}
+json operator "" _json(const char* s, std::size_t n);
+This operator implements a user-defined string literal for JSON objects. It can be used by adding _json to a string literal and returns a json object if no parse error occurred.
It is recommended to bring the operator into scope using any of the following lines:
using nlohmann::literals::operator "" _json;
+using namespace nlohmann::literals;
+using namespace nlohmann::json_literals;
+using namespace nlohmann::literals::json_literals;
+using namespace nlohmann;
+This is suggested to ease migration to the next major version release of the library. See 'JSON_USE_GLOBAL_UDLS` for details.
s (in)n (in)sjson value parsed from s
The function can throw anything that parse(s, s+n) would throw.
Linear.
The following code shows how to create JSON values from string literals.
#include <iostream>
+#include <iomanip>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+using namespace nlohmann::literals;
+
+int main()
+{
+ json j = R"( {"hello": "world", "answer": 42} )"_json;
+
+ std::cout << std::setw(2) << j << '\n';
+}
+Output:
{
+ "answer": 42,
+ "hello": "world"
+}
+nlohmann::literals::json_literals in 3.11.0.json_pointer operator "" _json_pointer(const char* s, std::size_t n);
+This operator implements a user-defined string literal for JSON Pointers. It can be used by adding _json_pointer to a string literal and returns a json_pointer object if no parse error occurred.
It is recommended to bring the operator into scope using any of the following lines:
using nlohmann::literals::operator "" _json_pointer;
+using namespace nlohmann::literals;
+using namespace nlohmann::json_literals;
+using namespace nlohmann::literals::json_literals;
+using namespace nlohmann;
+s (in)n (in)sjson_pointer value parsed from s
The function can throw anything that json_pointer::json_pointer would throw.
Linear.
The following code shows how to create JSON Pointers from string literals.
#include <iostream>
+#include <iomanip>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+using namespace nlohmann::literals;
+
+int main()
+{
+ json j = R"( {"hello": "world", "answer": 42} )"_json;
+ auto val = j["/hello"_json_pointer];
+
+ std::cout << std::setw(2) << val << '\n';
+}
+Output:
"world"
+nlohmann::literals::json_literals in 3.11.0.std::ostream& operator<<(std::ostream& o, const basic_json& j); // (1)
+
+std::ostream& operator<<(std::ostream& o, const json_pointer& ptr); // (2)
+j to the output stream o. The JSON value will be serialized using the dump member function.width of the output stream o. For instance, using the manipulator std::setw(4) on o sets the indentation level to 4 and the serialization result is the same as calling dump(4).fill of the output stream o. For instance, the manipulator std::setfill('\\t') sets indentation to use a tab character rather than the default space character.ptr to the output stream o. The string representation is obtained using the to_string member function.o (in, out)j (in)ptr (in)the stream o
type_error.316 if a string stored inside the JSON value is not UTF-8 encoded. Note that unlike the dump member functions, no error_handler can be set.Linear.
Deprecation
Function std::ostream& operator<<(std::ostream& o, const basic_json& j) replaces function std::ostream& operator>>(const basic_json& j, std::ostream& o) which has been deprecated in version 3.0.0. It will be removed in version 4.0.0. Please replace calls like j >> o; with o << j;.
The example below shows the serialization with different parameters to width to adjust the indentation level.
#include <iostream>
+#include <iomanip>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create JSON values
+ json j_object = {{"one", 1}, {"two", 2}};
+ json j_array = {1, 2, 4, 8, 16};
+
+ // serialize without indentation
+ std::cout << j_object << "\n\n";
+ std::cout << j_array << "\n\n";
+
+ // serialize with indentation
+ std::cout << std::setw(4) << j_object << "\n\n";
+ std::cout << std::setw(2) << j_array << "\n\n";
+ std::cout << std::setw(1) << std::setfill('\t') << j_object << "\n\n";
+}
+Output:
{"one":1,"two":2}
+
+[1,2,4,8,16]
+
+{
+ "one": 1,
+ "two": 2
+}
+
+[
+ 1,
+ 2,
+ 4,
+ 8,
+ 16
+]
+
+{
+ "one": 1,
+ "two": 2
+}
+The example below shows how to write a JSON pointer to a stream.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
+
+int main()
+{
+ // create JSON poiner
+ json::json_pointer ptr("/foo/bar/baz");
+
+ // write string representation to stream
+ std::cout << ptr << std::endl;
+}
+Output:
/foo/bar/baz
+std::ostream& operator>>(const basic_json& j, std::ostream& o) in version 3.0.0.using ordered_json = basic_json<ordered_map>;
+This type preserves the insertion order of object keys.
The example below demonstrates how ordered_json preserves the insertion order of object keys.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+using ordered_json = nlohmann::ordered_json;
+
+int main()
+{
+ ordered_json j;
+ j["one"] = 1;
+ j["two"] = 2;
+ j["three"] = 3;
+
+ std::cout << j.dump(2) << '\n';
+}
+Output:
{
+ "one": 1,
+ "two": 2,
+ "three": 3
+}
+Since version 3.9.0.
template<class Key, class T, class IgnoredLess = std::less<Key>,
+ class Allocator = std::allocator<std::pair<const Key, T>>>
+struct ordered_map : std::vector<std::pair<const Key, T>, Allocator>;
+A minimal map-like container that preserves insertion order for use within nlohmann::ordered_json (nlohmann::basic_json<ordered_map>).
KeyTIgnoredLessstd::map)AllocatorKey)T)std::vector<std::pair<const Key, T>, Allocator>)std::equal_to<Key> // until C++14
+
+std::equal_to<> // since C++14
+The example shows the different behavior of std::map and nlohmann::ordered_map.
#include <iostream>
+#include <nlohmann/json.hpp>
+
+// simple output function
+template<typename Map>
+void output(const char* prefix, const Map& m)
+{
+ std::cout << prefix << " = { ";
+ for (auto& element : m)
+ {
+ std::cout << element.first << ":" << element.second << ' ';
+ }
+ std::cout << "}" << std::endl;
+}
+
+int main()
+{
+ // create and fill two maps
+ nlohmann::ordered_map<std::string, std::string> m_ordered;
+ m_ordered["one"] = "eins";
+ m_ordered["two"] = "zwei";
+ m_ordered["three"] = "drei";
+
+ std::map<std::string, std::string> m_std;
+ m_std["one"] = "eins";
+ m_std["two"] = "zwei";
+ m_std["three"] = "drei";
+
+ // output: m_ordered is ordered by insertion order, m_std is ordered by key
+ output("m_ordered", m_ordered);
+ output("m_std", m_std);
+
+ // erase and re-add "one" key
+ m_ordered.erase("one");
+ m_ordered["one"] = "eins";
+
+ m_std.erase("one");
+ m_std["one"] = "eins";
+
+ // output: m_ordered shows newly added key at the end; m_std is again ordered by key
+ output("m_ordered", m_ordered);
+ output("m_std", m_std);
+}
+Output:
m_ordered = { one:eins two:zwei three:drei }
+m_std = { one:eins three:drei two:zwei }
+m_ordered = { two:zwei three:drei one:eins }
+m_std = { one:eins three:drei two:zwei }
+nlohmann::ordered_json.\n {translation(\"search.result.term.missing\")}: {...missing}\n
\n }\n