### Bazel Integration Setup Source: https://github.com/nlohmann/json/blob/develop/docs/mkdocs/docs/integration/package_managers.md Set up Bazel BUILD and MODULE.bazel files for nlohmann/json. Ensure your C++ example file includes the necessary dependency. ```ini --8<-- "integration/bazel/BUILD" ``` ```ini --8<-- "integration/bazel/MODULE.bazel" ``` -------------------------------- ### Spack CMakeLists.txt Example Source: https://github.com/nlohmann/json/blob/develop/docs/mkdocs/docs/integration/package_managers.md Example CMakeLists.txt file for a project using nlohmann-json installed via Spack. ```cmake cmake_minimum_required(VERSION 3.10) project("spack-example" VERSION 1.0) find_package(nlohmann_json REQUIRED) add_executable(example "example.cpp") target_link_libraries(example PRIVATE nlohmann_json::nlohmann_json) ``` -------------------------------- ### Meson Subproject Setup Source: https://github.com/nlohmann/json/blob/develop/docs/mkdocs/docs/integration/package_managers.md Example meson.build file for setting up nlohmann_json as a subproject. This allows direct inclusion of the library in your build. ```ini --8<-- "integration/meson/meson.build" ``` -------------------------------- ### Spack Example C++ Code Source: https://github.com/nlohmann/json/blob/develop/docs/mkdocs/docs/integration/package_managers.md A simple C++ example demonstrating the usage of nlohmann-json after installation with Spack. ```cpp #include #include using json = nlohmann::json; int main() { json j; j["name"] = "nlohmann-json"; j["version"] = "3.11.2"; std::cout << j.dump(4) << std::endl; return 0; } ``` -------------------------------- ### Conan Integration Setup Source: https://github.com/nlohmann/json/blob/develop/docs/mkdocs/docs/integration/package_managers.md Configure Conanfile.txt and CMakeLists.txt for nlohmann/json integration. The example C++ file demonstrates usage. ```ini --8<-- "integration/conan/Conanfile.txt" ``` ```cmake --8<-- "integration/conan/CMakeLists.txt" ``` ```cpp --8<-- "integration/conan/example.cpp" ``` -------------------------------- ### Amalgamate Installation and Testing Source: https://github.com/nlohmann/json/blob/develop/tools/amalgamate/README.md This command sequence shows how to test the amalgamate.py script and then install it to the system's binary path. ```bash ./test.sh && sudo -k cp ./amalgamate.py /usr/local/bin/ ``` -------------------------------- ### Conan Install and Build Commands Source: https://github.com/nlohmann/json/blob/develop/docs/mkdocs/docs/integration/package_managers.md Install dependencies using Conan and then build the project with CMake. ```shell conan install . --output-folder=build --build=missing cmake -S . -B build -DCMAKE_TOOLCHAIN_FILE="conan_toolchain.cmake" -DCMAKE_BUILD_TYPE=Release cmake --build build ``` -------------------------------- ### Start serve_header.py Source: https://github.com/nlohmann/json/blob/develop/tools/serve_header/README.md Run this command from the project root to start serving the json.hpp header file at https://localhost:8443/json.hpp. Ensure certificate files are in the project root. ```bash $ make serve_header ``` -------------------------------- ### Example Usage of binary() Source: https://github.com/nlohmann/json/blob/develop/docs/mkdocs/docs/api/basic_json/binary.md Demonstrates the creation of a binary JSON value using the `binary()` function. This example shows a practical application of the constructor. ```cpp --8<-- "examples/binary.cpp" ``` -------------------------------- ### CMakeLists.txt Integration Example Source: https://github.com/nlohmann/json/blob/develop/ChangeLog.md Example of how to integrate the nlohmann/json library into a CMake project using `add_subdirectory` and `target_link_libraries`. ```cmake # Top level CMakeLists.txt project(FOO) option(FOO_USE_EXTERNAL_JSON "Use an external JSON library" OFF) add_subdirectory(thirdparty) add_library(foo ...) # Note that the namespaced target will always be available regardless of the # import method target_link_libraries(foo PRIVATE nlohmann_json::nlohmann_json) ``` -------------------------------- ### Example Usage of Namespace Macros Source: https://github.com/nlohmann/json/blob/develop/docs/mkdocs/docs/api/macros/nlohmann_json_namespace_begin.md This example demonstrates how to use the NLOHMANN_JSON_NAMESPACE_BEGIN and NLOHMANN_JSON_NAMESPACE_END macros, as shown in the arbitrary types conversion feature. ```cpp --8<-- "examples/nlohmann_json_namespace_begin.c++17.cpp" ``` -------------------------------- ### C++ Example with Meson Subproject Source: https://github.com/nlohmann/json/blob/develop/docs/mkdocs/docs/integration/package_managers.md A basic C++ example demonstrating how to include and use nlohmann_json when integrated as a Meson subproject. Ensure your build system requires the nlohmann_json dependency. ```cpp --8<-- "integration/meson/example.cpp" ``` -------------------------------- ### Example: Accept JSON from a String Source: https://github.com/nlohmann/json/blob/develop/docs/mkdocs/docs/api/basic_json/accept.md Demonstrates how to use the `accept()` function to validate a JSON string. This example shows a successful validation. ```cpp --8<-- "examples/accept__string.cpp" ``` -------------------------------- ### Custom Exception Handling Example Source: https://github.com/nlohmann/json/blob/develop/docs/mkdocs/docs/api/macros/json_throw_user.md Example demonstrating how to switch off exceptions and create custom error logging with JSON_THROW_USER. ```cpp #include #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 ``` -------------------------------- ### Install nlohmann-json with Homebrew Source: https://github.com/nlohmann/json/blob/develop/docs/mkdocs/docs/integration/package_managers.md Use this command to install the nlohmann-json library via Homebrew. ```sh brew install nlohmann-json ``` -------------------------------- ### Output of to_string example Source: https://github.com/nlohmann/json/blob/develop/docs/mkdocs/docs/api/basic_json/to_string.md This shows the expected JSON output when using the `to_string` example. ```json --8<-- "examples/to_string.output" ``` -------------------------------- ### Example of cend() usage Source: https://github.com/nlohmann/json/blob/develop/docs/mkdocs/docs/api/basic_json/cend.md This example demonstrates how to use `cend()` in conjunction with `cbegin()` to iterate over a JSON array. ```cpp --8<-- "examples/cend.cpp" ``` -------------------------------- ### Example: JSON to MessagePack serialization Source: https://github.com/nlohmann/json/blob/develop/docs/mkdocs/docs/api/basic_json/to_msgpack.md Demonstrates the serialization of a JSON value to a byte vector in MessagePack format. Ensure the "examples/to_msgpack.cpp" file is available for this example. ```cpp --8<-- "examples/to_msgpack.cpp" ``` -------------------------------- ### Example: Switching Off Exceptions Source: https://github.com/nlohmann/json/blob/develop/docs/mkdocs/docs/api/macros/json_noexception.md This example demonstrates how to switch off exceptions by defining JSON_NOEXCEPTION before including the nlohmann/json header. ```cpp #define JSON_NOEXCEPTION 1 #include ... ``` -------------------------------- ### Example Meta Output Source: https://github.com/nlohmann/json/blob/develop/docs/mkdocs/docs/api/basic_json/meta.md This is an example of the JSON output from the `meta()` function. Note that the specific values for compiler, platform, and version will differ on your system. ```json --8<-- "examples/meta.output" ``` -------------------------------- ### vcpkg CMake Integration Example Source: https://github.com/nlohmann/json/blob/develop/docs/mkdocs/docs/integration/package_managers.md Example CMakeLists.txt and C++ source file for integrating nlohmann-json when using vcpkg. Ensure to set the CMAKE_TOOLCHAIN_FILE correctly. ```cmake --8<-- "integration/vcpkg/CMakeLists.txt" ``` ```cpp --8<-- "integration/vcpkg/example.cpp" ``` -------------------------------- ### Get Start Position of JSON Value Source: https://github.com/nlohmann/json/blob/develop/docs/mkdocs/docs/api/basic_json/start_pos.md This example demonstrates how to retrieve the starting character position of various JSON values after parsing. It requires the `JSON_DIAGNOSTIC_POSITIONS` macro to be defined. The positions are only valid if the JSON value has not been modified. ```cpp #include #include using json = nlohmann::json; int main() { // requires `JSON_DIAGNOSTIC_POSITIONS` to be defined // The example file `examples/diagnostic_positions.cpp` is used here. // The output is shown in `examples/diagnostic_positions.output`. // The following code is a conceptual representation of what might be in the example file: std::string text = R ``` -------------------------------- ### Bazel Build and Run Example Source: https://github.com/nlohmann/json/blob/develop/docs/mkdocs/docs/integration/package_managers.md Compile and execute a C++ program using Bazel after setting up the integration files. ```cpp --8<-- "integration/bazel/example.cpp" ``` ```shell bazel build //:main bazel run //:main ``` -------------------------------- ### Example: User-Defined Serialization/Deserialization Functions Source: https://github.com/nlohmann/json/blob/develop/docs/mkdocs/docs/api/macros/json_disable_enum_serialization.md This example demonstrates providing custom from_json and to_json functions to handle enum serialization and deserialization when JSON_DISABLE_ENUM_SERIALIZATION is enabled. ```cpp #define JSON_DISABLE_ENUM_SERIALIZATION 1 #include using json = nlohmann::json; enum class Choice { first, second, }; void from_json(const json& j, Choice& ch) { auto value = j.get(); if (value == "first") { ch = Choice::first; } else if (value == "second") { ch = Choice::second; } } void to_json(json& j, const Choice& ch) { if (ch == Choice::first) { j = "first"; } else if (ch == Choice::second) { j = "second"; } } int main() { // uses user-defined to_json function const json j = Choice::first; // uses user-defined from_json function Choice ch = j.get(); } ``` -------------------------------- ### Example Usage of get_allocator Source: https://github.com/nlohmann/json/blob/develop/docs/mkdocs/docs/api/basic_json/get_allocator.md This example shows how `get_allocator()` is used in practice to create JSON values. It retrieves the allocator and then uses it to construct a JSON object. ```cpp --8<-- "examples/get_allocator.cpp" ``` -------------------------------- ### Initialize, Build, and Test with build2 Source: https://github.com/nlohmann/json/blob/develop/docs/mkdocs/docs/integration/package_managers.md Commands to initialize a project with build2, download dependencies, build, and test the executable's output. ```shell cd example/ # create default C/C++ build configuration in ../example-myconfig/, initialize the project in it (downloads it's dependencies in it too) bdep init -C @myconfig cc # build only, b # or build and test the executable's output, will only work if the `testscript` is correct b test ``` -------------------------------- ### Get Iterator to First Element Source: https://github.com/nlohmann/json/blob/develop/docs/mkdocs/docs/api/basic_json/begin.md This example demonstrates how to use the `begin()` function to get an iterator to the first element of a JSON array and access its value. ```cpp --8<-- "examples/begin.cpp" ``` ```json --8<-- "examples/begin.output" ``` -------------------------------- ### Generate Local Documentation Source: https://github.com/nlohmann/json/blob/develop/docs/README.md Clone the repository, checkout a specific tag, and use make to install dependencies and serve the documentation locally. Open the provided URL in your browser to view the documentation for the selected version. ```shell git clone https://github.com/nlohmann/json.git cd json git checkout v3.10.2 make install_venv serve -C docs/mkdocs ``` -------------------------------- ### Get Pointer to Internal JSON Value - Example Source: https://github.com/nlohmann/json/blob/develop/docs/mkdocs/docs/api/basic_json/get_ptr.md This example illustrates requesting pointers to internal values within a JSON structure. It highlights that type mismatches result in a `nullptr` return, as no automatic type conversions occur. ```cpp --8<-- "examples/get_ptr.cpp" ``` -------------------------------- ### Example C++ code using nlohmann/json with build2 Source: https://github.com/nlohmann/json/blob/develop/docs/mkdocs/docs/integration/package_managers.md This is a basic 'hello world' example that replaces the default generated code. It demonstrates the usage of the nlohmann/json library after it has been integrated via build2. ```cpp #include #include using json = nlohmann::json; int main() { json j; j["name"] = "nlohmann/json"; j["version"] = "3.11.2"; std::cout << j.dump(4) << std::endl; } ``` -------------------------------- ### Get end position of a JSON value Source: https://github.com/nlohmann/json/blob/develop/docs/mkdocs/docs/api/basic_json/end_pos.md This example demonstrates how to retrieve the end position of a JSON value. The function is only available if `JSON_DIAGNOSTIC_POSITIONS` is defined. ```cpp #include #include using json = nlohmann::json; int main() { // define the macro to enable diagnostic positions // #define JSON_DIAGNOSTIC_POSITIONS 1 // parse a JSON string json j = json::parse(R"({ "foo": 1, "bar": null, "baz": [ 1, 2 ] }")"); // get the end position of the JSON value auto end_pos = j.end_pos(); // print the end position std::cout << "End position: " << end_pos << std::endl; return 0; } ``` -------------------------------- ### Usage of front() Source: https://github.com/nlohmann/json/blob/develop/docs/mkdocs/docs/api/json_pointer/front.md This example demonstrates how to use the `front` method to retrieve the first reference token of a JSON pointer. Ensure the JSON pointer has a parent to avoid exceptions. ```cpp #include #include int main() { // create a JSON pointer nlohmann::json_pointer<> ptr("/foo/0/bar"); // get the first reference token std::cout << ptr.front() << std::endl; // create a JSON pointer with no parent nlohmann::json_pointer<> ptr2; try { ptr2.front(); } catch (nlohmann::json_pointer_exceptions::out_of_range &e) { std::cerr << "Exception: " << e.what() << std::endl; } } ``` ```json foo Exception: out of range: JSON pointer has no parent ``` -------------------------------- ### Example: Default-Constructible Type Conversion Source: https://github.com/nlohmann/json/blob/develop/docs/mkdocs/docs/api/adl_serializer/from_json.md Demonstrates implementing `from_json` for a user-defined, default-constructible type. This function is invoked by `adl_serializer` when `get()` is called. ```cpp --8<-- "examples/from_json__default_constructible.cpp" ``` -------------------------------- ### Get size of different JSON value types Source: https://github.com/nlohmann/json/blob/develop/docs/mkdocs/docs/api/basic_json/size.md This example demonstrates calling `size()` on various JSON value types to observe the returned element count. ```cpp --8<-- "examples/size.cpp" ``` -------------------------------- ### Example: Count number of elements using string_view Source: https://github.com/nlohmann/json/blob/develop/docs/mkdocs/docs/api/basic_json/count.md Shows how to use the `count()` method with a `string_view` as the key type, leveraging C++17 features for efficient key lookup. ```cpp --8<-- "examples/count__keytype.c++17.cpp" ``` -------------------------------- ### Example C++ code for Conda integration Source: https://github.com/nlohmann/json/blob/develop/docs/mkdocs/docs/integration/package_managers.md This C++ file demonstrates usage after installing the library via Conda. Ensure the environment is activated and the compiler can find the headers. ```cpp --8<-- "integration/conda/example.cpp" ``` -------------------------------- ### Example Namespace Name Source: https://github.com/nlohmann/json/blob/develop/docs/mkdocs/docs/features/namespace.md Illustrates the fully qualified namespace name for a specific version and configuration. ```cpp nlohmann::json_abi_diag_v3_11_2 ``` -------------------------------- ### Get JSON Type Name Source: https://github.com/nlohmann/json/blob/develop/docs/mkdocs/docs/api/basic_json/type_name.md This example demonstrates how to retrieve the type name for various JSON types using the `type_name()` method. It covers all supported JSON types. ```cpp nlohmann::json j; std::cout << "null: " << j.type_name() << std::endl; j = true; std::cout << "boolean: " << j.type_name() << std::endl; j = "hello"; std::cout << "string: " << j.type_name() << std::endl; j = 123; std::cout << "number (integer): " << j.type_name() << std::endl; j = 123.456; std::cout << "number (floating-point): " << j.type_name() << std::endl; j = {{"foo", "bar"}}; std::cout << "object: " << j.type_name() << std::endl; j = {1, 2, 3}; std::cout << "array: " << j.type_name() << std::endl; j = nlohmann::json::binary({1, 2, 3}); std::cout << "binary: " << j.type_name() << std::endl; j.discarded(); std::cout << "discarded: " << j.type_name() << std::endl; ``` -------------------------------- ### Configure serve_header.py with YAML Source: https://github.com/nlohmann/json/blob/develop/tools/serve_header/README.md Create a serve_header.yml file in the project root to configure the server. This example shifts the web server root directory up one level to support multiple working trees. ```yaml root: .. ``` -------------------------------- ### Get JSON Value Type Source: https://github.com/nlohmann/json/blob/develop/docs/mkdocs/docs/api/basic_json/type.md This example demonstrates how to use the `type()` function to determine the type of various JSON values. It covers all possible return types of the `type()` function. ```cpp --8<-- "examples/type.cpp" ``` ```json --8<-- "examples/type.output" ``` -------------------------------- ### Get reverse iterator to end of JSON object Source: https://github.com/nlohmann/json/blob/develop/docs/mkdocs/docs/api/basic_json/crend.md This example demonstrates how to use `crend()` to obtain a reverse iterator to the end of a JSON object. The output shows the JSON structure. ```cpp const_reverse_iterator crend() const noexcept; ``` ```cpp --8<-- "examples/crend.cpp" ``` -------------------------------- ### Example: Using Only Diagnostic Positions in Exceptions Source: https://github.com/nlohmann/json/blob/develop/docs/mkdocs/docs/api/macros/json_diagnostics.md Shows how to configure exceptions to include only the start and end positions of the problematic element, without necessarily enabling full JSON Pointer diagnostics. ```cpp --8<-- "examples/diagnostic_positions_exception.cpp" ``` -------------------------------- ### Retrieve Positions of Parsed JSON Values Source: https://github.com/nlohmann/json/blob/develop/docs/mkdocs/docs/api/macros/json_diagnostic_positions.md This example demonstrates how to retrieve the start and end byte positions of JSON values after parsing. The positions correspond to the characters in the original JSON string. ```cpp --8<-- "examples/diagnostic_positions.cpp" ``` -------------------------------- ### Basic JSON Example Source: https://github.com/nlohmann/json/blob/develop/docs/mkdocs/docs/api/basic_json/index.md This example demonstrates fundamental usage of the nlohmann/json library, showing how to create, manipulate, and serialize JSON data. It covers basic object and array creation, value assignment, and outputting the JSON structure. ```cpp --8<-- "examples/README.cpp" ``` ```json --8<-- "examples/README.output" ``` -------------------------------- ### CMake Project Setup and Dependency Find Source: https://github.com/nlohmann/json/blob/develop/tests/cmake_import_minver/project/CMakeLists.txt Configures the CMake project and finds the nlohmann_json library with a specific version requirement. Ensure the nlohmann_json library is installed or available in the CMake search path. ```cmake cmake_minimum_required(VERSION 3.5...3.14) project(DummyImportMinVer CXX) find_package(nlohmann_json 3.2.0 REQUIRED) ``` -------------------------------- ### Install nlohmann-json with vcpkg Source: https://github.com/nlohmann/json/blob/develop/docs/mkdocs/docs/integration/package_managers.md Use vcpkg to install the nlohmann-json package. This command installs the library for use in your C++ projects. ```shell vcpkg install nlohmann-json ``` -------------------------------- ### Example of push_front for JSON Pointers Source: https://github.com/nlohmann/json/blob/develop/docs/mkdocs/docs/api/json_pointer/push_front.md Demonstrates the effect of the push_front method on various JSON Pointers. The output shows the resulting JSON Pointer after the token has been prepended. ```cpp #include #include int main() { // example 1 nlohmann::json_pointer<> ptr1("/foo/bar"); ptr1.push_front("baz"); std::cout << ptr1 << std::endl; // example 2 nlohmann::json_pointer<> ptr2; ptr2.push_front("a"); ptr2.push_front("b"); std::cout << ptr2 << std::endl; // example 3 nlohmann::json_pointer<> ptr3("/"); ptr3.push_front("a"); std::cout << ptr3 << std::endl; // example 4 nlohmann::json_pointer<> ptr4("/"); ptr4.push_front(""); std::cout << ptr4 << std::endl; // example 5 nlohmann::json_pointer<> ptr5("/"); ptr5.push_front("a"); ptr5.push_front(""); std::cout << ptr5 << std::endl; return 0; } ``` ```json /baz/foo/bar /b/a /a / //a ``` -------------------------------- ### Example packages.config for NuGet Source: https://github.com/nlohmann/json/blob/develop/docs/mkdocs/docs/integration/package_managers.md This XML file lists the NuGet packages required by a project, including their IDs and versions. It is essential for package restoration. ```xml ``` -------------------------------- ### Example of string_t Usage Source: https://github.com/nlohmann/json/blob/develop/docs/mkdocs/docs/api/json_pointer/string_t.md This example demonstrates the `string_t` type and its relationship with `basic_json::string_t`. It includes the C++ code for the example and its expected JSON output. ```cpp --8<-- "examples/json_pointer__string_t.cpp" ``` ```json --8<-- "examples/json_pointer__string_t.output" ``` -------------------------------- ### Install nlohmann-json with MacPorts Source: https://github.com/nlohmann/json/blob/develop/docs/mkdocs/docs/integration/package_managers.md Use this command to install the nlohmann-json package if you are using MacPorts. ```shell sudo port install nlohmann-json ``` -------------------------------- ### Example: Comparing JSON Pointers Source: https://github.com/nlohmann/json/blob/develop/docs/mkdocs/docs/api/json_pointer/operator_eq.md Demonstrates comparing JSON pointers for equality. ```cpp --8<-- "examples/json_pointer__operator__equal.cpp" ``` -------------------------------- ### Example Usage of byte_container_with_subtype Source: https://github.com/nlohmann/json/blob/develop/docs/mkdocs/docs/api/byte_container_with_subtype/byte_container_with_subtype.md Demonstrates the creation and usage of byte containers with and without subtypes. ```cpp --8<-- "examples/byte_container_with_subtype__byte_container_with_subtype.cpp" ``` -------------------------------- ### Install nlohmann_json with Conda Source: https://github.com/nlohmann/json/blob/develop/docs/mkdocs/docs/integration/package_managers.md Use this command to install the nlohmann_json package from the conda-forge channel. ```shell conda install -c conda-forge nlohmann_json ``` -------------------------------- ### Constructor from Initializer List (Example 5) Source: https://github.com/nlohmann/json/blob/develop/docs/mkdocs/docs/api/basic_json/basic_json.md Demonstrates constructing JSON arrays or objects directly from C++ initializer lists. ```APIDOC ## basic_json(std::initializer_list init) ### Description Constructs a JSON container (array or object) from a C++ initializer list. This provides a convenient syntax for creating JSON structures inline. ### Method Constructor ### Parameters - **init** (std::initializer_list) - An initializer list containing `basic_json` values to populate the container. ### Response #### Success Response (Implicit) - Returns a `basic_json` object (array or object) populated with the elements from the initializer list. ``` -------------------------------- ### JSON Text Example Source: https://github.com/nlohmann/json/blob/develop/docs/mkdocs/docs/features/parsing/json_lines.md This is an example of text formatted according to the JSON Lines specification. ```json {"name": "Gilbert", "wins": [["straight", "7♣"], ["one pair", "10♥"]]} {"name": "Alexa", "wins": [["two pair", "4♠"], ["two pair", "9♠"]]} {"name": "May", "wins": []} {"name": "Deloise", "wins": [["three of a kind", "5♣"]]} ``` -------------------------------- ### Example Usage of operator/ Source: https://github.com/nlohmann/json/blob/develop/docs/mkdocs/docs/api/json_pointer/operator_slash.md Demonstrates the usage of the operator/ for appending tokens and JSON pointers to create new JSON pointers. The output shows the resulting JSON pointers. ```cpp --8<-- "examples/json_pointer__operator_add_binary.cpp" ``` -------------------------------- ### Example: Find object element by key Source: https://github.com/nlohmann/json/blob/develop/docs/mkdocs/docs/api/basic_json/find.md Demonstrates the usage of the `find()` method to locate an object element using its key. ```cpp #include #include using json = nlohmann::json; int main() { json j = R"({ "foo": 1, "bar": 2 })"_json; // find an element auto it = j.find("foo"); // check if found if (it != j.end()) { std::cout << "found: " << it.key() << " = " << it.value() << std::endl; } else { std::cout << "not found" << std::endl; } // find an element that is not there it = j.find("baz"); if (it != j.end()) { std::cout << "found: " << it.key() << " = " << it.value() << std::endl; } else { std::cout << "not found" << std::endl; } // example with a non-object json j_array = { 1, 2 }; it = j_array.find("foo"); if (it != j_array.end()) { std::cout << "found: " << it.key() << " = " << it.value() << std::endl; } else { std::cout << "not found" << std::endl; } return 0; } ``` ```json found: foo = 1 not found not found ``` -------------------------------- ### Install Python Packages Source: https://github.com/nlohmann/json/blob/develop/tools/serve_header/README.md Ensure these Python packages are installed before running the script. They are listed in requirements.txt. ```bash PyYAML watchdog ``` -------------------------------- ### Add GDB Pretty Printer to .gdbinit Source: https://github.com/nlohmann/json/blob/develop/tools/gdb_pretty_printer/README.md Add this line to your ~/.gdbinit file to automatically load the pretty printer script when GDB starts. Ensure you replace '/path/to/' with the actual path to the script. ```shell source /path/to/nlohmann-json.py ``` -------------------------------- ### Output for is_boolean() example Source: https://github.com/nlohmann/json/blob/develop/docs/mkdocs/docs/api/basic_json/is_boolean.md This shows the expected JSON output when running the `is_boolean()` example code. ```json --8<-- "examples/is_boolean.output" ``` -------------------------------- ### Install nlohmann-json with Spack Source: https://github.com/nlohmann/json/blob/develop/docs/mkdocs/docs/integration/package_managers.md Use this command to install the nlohmann-json package using the Spack package manager. ```shell spack install nlohmann-json ``` -------------------------------- ### Example: Comparing JSON pointers Source: https://github.com/nlohmann/json/blob/develop/docs/mkdocs/docs/api/json_pointer/operator_ne.md Demonstrates comparing JSON pointers for inequality. ```cpp #include #include int main() { nlohmann::json_pointer<> ptr1("/foo/0/bar"); nlohmann::json_pointer<> ptr2("/foo/1/bar"); nlohmann::json_pointer<> ptr3("/foo/0/bar"); // (1) compare JSON pointers std::cout << std::boolalpha; std::cout << (ptr1 != ptr2) << std::endl; std::cout << (ptr1 != ptr3) << std::endl; } ``` -------------------------------- ### Example Usage of NLOHMANN_JSON_NAMESPACE_NO_VERSION Source: https://github.com/nlohmann/json/blob/develop/docs/mkdocs/docs/api/macros/nlohmann_json_namespace_no_version.md This example demonstrates how to use NLOHMANN_JSON_NAMESPACE_NO_VERSION to disable the version component of the inline namespace. ```cpp --8<-- "examples/nlohmann_json_namespace_no_version.cpp" ``` -------------------------------- ### GPLv3 Notice for Interactive Programs Source: https://github.com/nlohmann/json/blob/develop/LICENSES/GPL-3.0-only.txt Display this short notice when a program starts in interactive mode to inform users about warranty, distribution, and modification rights. The commands 'show w' and 'show c' should display relevant license sections. ```text Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. ``` -------------------------------- ### Example: Add to object from initializer list Source: https://github.com/nlohmann/json/blob/develop/docs/mkdocs/docs/api/basic_json/operator+=.md Shows how initializer lists are treated as objects when they meet specific criteria, allowing for direct object construction or addition. ```cpp nlohmann::json j; j += {"key", "value"}; std::cout << j << std::endl; j.clear(); j += {"key", "value", "key2", "value2"}; std::cout << j << std::endl; ``` -------------------------------- ### JSON with Comments Example Source: https://github.com/nlohmann/json/blob/develop/docs/mkdocs/docs/features/comments.md This example shows a JSON structure containing both line comments (//) and block comments (/* */). ```json { // update in 2006: removed Pluto "planets": ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Uranus", "Neptune" /*, "Pluto" */] } ``` -------------------------------- ### Example: Switching on Legacy Discarded Value Comparison Source: https://github.com/nlohmann/json/blob/develop/docs/mkdocs/docs/api/macros/json_use_legacy_discarded_value_comparison.md This example demonstrates how to switch on the legacy discarded value comparison behavior by defining the macro to 1. This should be done before including the library header. ```cpp #define JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON 1 #include ... ``` -------------------------------- ### JSON Lines Output Example Source: https://github.com/nlohmann/json/blob/develop/docs/mkdocs/docs/features/parsing/json_lines.md The expected output when processing the JSON Lines input example line by line. ```json --8<-- "examples/json_lines.output" ``` -------------------------------- ### Example Usage of basic_json::array Source: https://github.com/nlohmann/json/blob/develop/docs/mkdocs/docs/api/basic_json/array.md This example demonstrates how to use the `array` function to create a JSON array with various types of elements. It also shows the output produced by the function. ```cpp #include #include using json = nlohmann::json; int main() { // create an empty array json j1 = json::array(); // create an array from an initializer list json j2 = json::array({"hello", "world"}); // create an array from an initializer list with objects json j3 = json::array({{ {"greeting", "hello"}, {"language", "en"} }}); // create an array from an initializer list with arrays json j4 = json::array({{1, 2, 3}, {4, 5, 6}}); // create an array from an initializer list with mixed types json j5 = json::array({1, "hello", {"key", "value"}, {1, 2}}); // output std::cout << j1 << std::endl; std::cout << j2 << std::endl; std::cout << j3 << std::endl; std::cout << j4 << std::endl; std::cout << j5 << std::endl; } ``` -------------------------------- ### Install nlohmann-json with MSYS2 Source: https://github.com/nlohmann/json/blob/develop/docs/mkdocs/docs/integration/package_managers.md Install the nlohmann-json package for MSYS2 using pacman. Choose the appropriate architecture (i686 or x86_64). ```shell pacman -S mingw-w64-i686-nlohmann-json ``` ```shell pacman -S mingw-w64-x86_64-nlohmann-json ``` -------------------------------- ### Example: Basic update operation Source: https://github.com/nlohmann/json/blob/develop/docs/mkdocs/docs/api/basic_json/update.md Demonstrates a basic usage of the `update` function with a JSON object. ```cpp --8<-- "examples/update.cpp" ``` ```json --8<-- "examples/update.output" ``` -------------------------------- ### SAX Interface Usage Example Source: https://github.com/nlohmann/json/blob/develop/docs/mkdocs/docs/api/json_sax/start_object.md Demonstrates how to use the SAX interface, including the start_object method, within a C++ application. This snippet requires the 'sax_parse.cpp' file for its implementation. ```cpp virtual bool start_object(std::size_t elements) = 0; ``` ```cpp --8<-- "examples/sax_parse.cpp" ``` -------------------------------- ### Enable Experimental Filesystem Support Source: https://github.com/nlohmann/json/blob/develop/docs/mkdocs/docs/api/macros/json_has_filesystem.md Force the library to use the header by defining the JSON_HAS_EXPERIMENTAL_FILESYSTEM macro. This is useful when the automatic detection might not be accurate or when targeting specific compiler/library versions. ```cpp #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1 #include ... ``` -------------------------------- ### Example: Forcing JSON_NO_IO definition Source: https://github.com/nlohmann/json/blob/develop/docs/mkdocs/docs/api/macros/json_no_io.md This example demonstrates how to define JSON_NO_IO to prevent the library from using I/O stream headers. ```cpp #define JSON_NO_IO 1 #include ... ```