This commit is contained in:
nlohmann
2026-10-12 07:35:31 +00:00
parent 79119509a9
commit 22fba27145
555 changed files with 17342 additions and 1394 deletions
+1 -1
View File
File diff suppressed because one or more lines are too long
+96 -4
View File
@@ -41,13 +41,51 @@ class (either explicitly or via the conversion operators).
called by the `adl_serializer` when `get<ns::person>()` is called.
```cpp
--8<-- "examples/from_json__default_constructible.cpp"
#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:
```json
--8<-- "examples/from_json__default_constructible.output"
Ned Flanders (60) lives in 744 Evergreen Terrace
```
??? example "Example: (2) Non-default-constructible type"
@@ -56,13 +94,67 @@ class (either explicitly or via the conversion operators).
realize the conversion of a non-default-constructible type.
```cpp
--8<-- "examples/from_json__non_default_constructible.cpp"
#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:
```json
--8<-- "examples/from_json__non_default_constructible.output"
Ned Flanders (60) lives in 744 Evergreen Terrace
```
## See also
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+35 -2
View File
@@ -25,13 +25,46 @@ This function is usually called by the constructors of the [basic_json](../basic
by the `adl_serializer` when the constructor `basic_json(ns::person)` is called.
```cpp
--8<-- "examples/to_json.cpp"
#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:
```json
--8<-- "examples/to_json.output"
{"address":"744 Evergreen Terrace","age":60,"name":"Ned Flanders"}
```
## See also
File diff suppressed because one or more lines are too long
+69 -2
View File
@@ -285,6 +285,7 @@ Access to the JSON value
### JSON Merge Patch functions
- [**merge_patch**](merge_patch.md) - applies a JSON Merge Patch
- [**merge_diff**](merge_diff.md) (_static_) - creates a diff as a JSON Merge Patch
## Static functions
@@ -330,13 +331,79 @@ Access to the JSON value
The example shows how the library is used.
```cpp
--8<-- "examples/README.cpp"
#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:
```json
--8<-- "examples/README.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
}
```
## See also
+47 -4
View File
@@ -101,13 +101,40 @@ outside of a string, invalid) byte; see the [FAQ entry](../../home/faq.md#nul-by
The example below demonstrates the `accept()` function reading from a string.
```cpp
--8<-- "examples/accept__string.cpp"
#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:
```json
--8<-- "examples/accept__string.output"
true false
```
??? example "Example: (2) reading from an iterator pair"
@@ -116,13 +143,29 @@ outside of a string, invalid) byte; see the [FAQ entry](../../home/faq.md#nul-by
exactly the JSON text; the second one also covers the trailing bytes and is therefore rejected.
```cpp
--8<-- "examples/accept__iterator_pair.cpp"
#include <iostream>
#include <vector>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
// a buffer containing a JSON text followed by more data
std::vector<std::uint8_t> input = {'[', '1', ',', '2', ',', '3', ']', 'o', 't', 'h', 'e', 'r'};
std::cout << std::boolalpha
<< json::accept(input.begin(), input.begin() + 7) << ' '
<< json::accept(input.begin(), input.end()) << '\n';
}
```
Output:
```json
--8<-- "examples/accept__iterator_pair.output"
true false
```
## See also
File diff suppressed because one or more lines are too long
+25 -2
View File
@@ -41,13 +41,36 @@ This function is only needed to express two edge cases that cannot be realized w
The following code shows an example for the `array` function.
```cpp
--8<-- "examples/array.cpp"
#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:
```json
--8<-- "examples/array.output"
[]
[]
[1,2,3,4]
[["one",1],["two",2]]
```
## See also
File diff suppressed because one or more lines are too long
+13 -2
View File
@@ -58,13 +58,24 @@ Arrays are stored as pointers in a `basic_json` type. That is, for any access to
The following code shows that `array_t` is by default, a typedef to `#!cpp std::vector<nlohmann::json>`.
```cpp
--8<-- "examples/array_t.cpp"
#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:
```json
--8<-- "examples/array_t.output"
true
```
## See also
File diff suppressed because one or more lines are too long
+33 -2
View File
@@ -35,13 +35,44 @@ The function is equivalent to `static_cast<json_base_class_t&>(j)` (or `static_c
of `basic_json`.
```cpp
--8<-- "examples/as_base_class.cpp"
#include <iostream>
#include <nlohmann/json.hpp>
class base_class_with_hidden_members
{
public:
const char* type_name() const noexcept
{
return "my_type_name";
}
std::size_t size() const noexcept
{
return 42;
}
};
using json = nlohmann::json::with_base_class_t<base_class_with_hidden_members>;
int main()
{
json j = {1, 2, 3};
// the members of basic_json hide the members of the base class
std::cout << j.type_name() << ' ' << j.size() << '\n';
// access the hidden members of the base class
std::cout << j.as_base_class().type_name() << ' ' << j.as_base_class().size() << '\n';
}
```
Output:
```json
--8<-- "examples/as_base_class.output"
array 3
my_type_name 42
```
## See also
File diff suppressed because one or more lines are too long
+502 -17
View File
@@ -114,13 +114,59 @@ Strong exception safety: if an exception occurs, the original value stays intact
exceptions that can be thrown.
```cpp
--8<-- "examples/at__size_type.cpp"
#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 (const 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 (const json::out_of_range& e)
{
std::cout << e.what() << '\n';
}
}
```
Output:
```json
--8<-- "examples/at__size_type.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
```
??? example "Example: (1) access specified array element with bounds checking"
@@ -129,13 +175,52 @@ Strong exception safety: if an exception occurs, the original value stays intact
that can be thrown.
```cpp
--8<-- "examples/at__size_type_const.cpp"
#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 (const 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 (const json::out_of_range& e)
{
std::cout << e.what() << '\n';
}
}
```
Output:
```json
--8<-- "examples/at__size_type_const.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
```
??? example "Example: (2) access specified object element with bounds checking"
@@ -144,13 +229,64 @@ Strong exception safety: if an exception occurs, the original value stays intact
exceptions that can be thrown.
```cpp
--8<-- "examples/at__object_t_key_type.cpp"
#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 (const 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 (const json::out_of_range& e)
{
std::cout << e.what() << '\n';
}
}
```
Output:
```json
--8<-- "examples/at__object_t_key_type.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
```
??? example "Example: (2) access specified object element with bounds checking"
@@ -159,13 +295,57 @@ Strong exception safety: if an exception occurs, the original value stays intact
that can be thrown.
```cpp
--8<-- "examples/at__object_t_key_type_const.cpp"
#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 (const 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 (const json::out_of_range)
{
std::cout << "out of range" << '\n';
}
}
```
Output:
```json
--8<-- "examples/at__object_t_key_type_const.output"
"il brutto"
[json.exception.type_error.304] cannot use at() with string
out of range
```
??? example "Example: (3) access specified object element using string_view with bounds checking"
@@ -174,13 +354,66 @@ Strong exception safety: if an exception occurs, the original value stays intact
exceptions that can be thrown.
```cpp
--8<-- "examples/at__keytype.c++17.cpp"
#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 (const 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 (const json::out_of_range& e)
{
std::cout << e.what() << '\n';
}
}
```
Output:
```json
--8<-- "examples/at__keytype.c++17.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
```
??? example "Example: (3) access specified object element using string_view with bounds checking"
@@ -189,13 +422,59 @@ Strong exception safety: if an exception occurs, the original value stays intact
that can be thrown.
```cpp
--8<-- "examples/at__keytype_const.c++17.cpp"
#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 (const 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 (const json::out_of_range& e)
{
std::cout << "out of range" << '\n';
}
}
```
Output:
```json
--8<-- "examples/at__keytype_const.c++17.output"
"il brutto"
[json.exception.type_error.304] cannot use at() with string
out of range
```
??? example "Example: (4) access specified element via JSON Pointer"
@@ -204,13 +483,128 @@ Strong exception safety: if an exception occurs, the original value stays intact
exceptions that can be thrown.
```cpp
--8<-- "examples/at__json_pointer.cpp"
#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 (const 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 (const 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 (const 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 (const 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 (const 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 (const json::out_of_range& e)
{
std::cout << e.what() << '\n';
}
}
```
Output:
```json
--8<-- "examples/at__json_pointer.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'
```
??? example "Example: (4) access specified element via JSON Pointer"
@@ -219,13 +613,102 @@ Strong exception safety: if an exception occurs, the original value stays intact
that can be thrown.
```cpp
--8<-- "examples/at__json_pointer_const.cpp"
#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 (const 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 (const 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 (const 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 (const 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 (const json::out_of_range& e)
{
std::cout << e.what() << '\n';
}
}
```
Output:
```json
--8<-- "examples/at__json_pointer_const.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'
```
## See also
@@ -241,4 +724,6 @@ Strong exception safety: if an exception occurs, the original value stays intact
3. Added in version 3.11.0. Fixed in version 3.13.0 to consistently accept `std::string_view`-convertible keys, as
already supported by [`operator[]`](operator[].md), [`value`](value.md), [`find`](find.md), and other lookup
functions.
4. Added in version 2.0.0.
4. Added in version 2.0.0. Throws [`parse_error.109`](../../home/exceptions.md#jsonexceptionparse_error109) instead of
[`out_of_range.404`](../../home/exceptions.md#jsonexceptionout_of_range404) for a one-character array index that is not
a digit (e.g., `/x`) in version 3.13.0, as it already did for longer ones.
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -675,4 +675,4 @@ Output:
1. Added in version 1.0.0.
1. Added in version 1.0.0.
1. Added in version 3.11.0. Fixed in version 3.13.0 unreleased to consistently accept `std::string_view`-convertible keys, as already supported by [`operator[]`](https://json.nlohmann.me/api/basic_json/operator%5B%5D/index.md), [`value`](https://json.nlohmann.me/api/basic_json/value/index.md), [`find`](https://json.nlohmann.me/api/basic_json/find/index.md), and other lookup functions.
1. Added in version 2.0.0.
1. Added in version 2.0.0. Throws [`parse_error.109`](https://json.nlohmann.me/home/exceptions/#jsonexceptionparse_error109) instead of [`out_of_range.404`](https://json.nlohmann.me/home/exceptions/#jsonexceptionout_of_range404) for a one-character array index that is not a digit (e.g., `/x`) in version 3.13.0 unreleased, as it already did for longer ones.
+47 -2
View File
@@ -46,13 +46,58 @@ Constant.
The following code shows an example for `back()`.
```cpp
--8<-- "examples/back.cpp"
#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 (const json::invalid_iterator& e)
{
std::cout << e.what() << '\n';
}
}
```
Output:
```json
--8<-- "examples/back.output"
true
17
23.42
2
16
"Hello, world"
[json.exception.invalid_iterator.214] cannot get value
```
## See also
File diff suppressed because one or more lines are too long
+467 -18
View File
@@ -336,13 +336,45 @@ basic_json(basic_json&& other) noexcept;
The following code shows the constructor for different `value_t` values.
```cpp
--8<-- "examples/basic_json__value_t.cpp"
#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:
```json
--8<-- "examples/basic_json__value_t.output"
null
false
0
0.0
{}
[]
""
```
??? example "Example: (2) create a `#!json null` object"
@@ -350,13 +382,31 @@ basic_json(basic_json&& other) noexcept;
The following code shows the constructor with and without a null pointer parameter.
```cpp
--8<-- "examples/basic_json__nullptr_t.cpp"
#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:
```json
--8<-- "examples/basic_json__nullptr_t.output"
null
null
```
??? example "Example: (3) create a JSON value from compatible types"
@@ -364,13 +414,266 @@ basic_json(basic_json&& other) noexcept;
The following code shows the constructor with several compatible types.
```cpp
--8<-- "examples/basic_json__CompatibleType.cpp"
#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", false}
};
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", "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", "one"};
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:
```json
--8<-- "examples/basic_json__CompatibleType.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"]
["one"]
["four","one","one","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.
@@ -382,13 +685,38 @@ basic_json(basic_json&& other) noexcept;
converting to `json`, whose `object_t` sorts by key.
```cpp
--8<-- "examples/basic_json__BasicJsonType.cpp"
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
using ordered_json = nlohmann::ordered_json;
int main()
{
// create an ordered_json value; insertion order is preserved
ordered_json oj = {{"c", 3}, {"a", 1}, {"b", 2}};
// convert to json -- overload (4) is used; keys end up sorted
json j(oj);
// convert back to ordered_json -- the original insertion order is lost,
// because it was already given up when converting to json
ordered_json oj2(j);
std::cout << oj << '\n';
std::cout << j << '\n';
std::cout << oj2 << '\n';
}
```
Output:
```json
--8<-- "examples/basic_json__BasicJsonType.output"
{"c":3,"a":1,"b":2}
{"a":1,"b":2,"c":3}
{"a":1,"b":2,"c":3}
```
??? example "Example: (5) create a container (array or object) from an initializer list"
@@ -396,13 +724,39 @@ basic_json(basic_json&& other) noexcept;
The example below shows how JSON values are created from initializer lists.
```cpp
--8<-- "examples/basic_json__list_init_t.cpp"
#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:
```json
--8<-- "examples/basic_json__list_init_t.output"
{}
{"one":1,"two":2}
[1,2,3,4]
{"one":[1],"two":[1,2]}
[[[1],"one"],[[1,2],"two"]]
```
??? example "Example: (6) construct an array with count copies of a given value"
@@ -410,13 +764,34 @@ basic_json(basic_json&& other) noexcept;
The following code shows examples for creating arrays with several copies of a given value.
```cpp
--8<-- "examples/basic_json__size_type_basic_json.cpp"
#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:
```json
--8<-- "examples/basic_json__size_type_basic_json.output"
[]
["Hello"]
["Hello","Hello","Hello","Hello","Hello"]
```
??? example "Example: (7) construct a JSON container given an iterator range"
@@ -424,13 +799,49 @@ basic_json(basic_json&& other) noexcept;
The example below shows several ways to create JSON values by specifying a subrange with iterators.
```cpp
--8<-- "examples/basic_json__InputIt_InputIt.cpp"
#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 (const json::invalid_iterator& e)
{
std::cout << e.what() << '\n';
}
}
```
Output:
```json
--8<-- "examples/basic_json__InputIt_InputIt.output"
["bravo","charly"]
42
{"one":"eins"}
[json.exception.invalid_iterator.204] iterators out of range
```
??? example "Example: (8) copy constructor"
@@ -438,13 +849,32 @@ basic_json(basic_json&& other) noexcept;
The following code shows an example for the copy constructor.
```cpp
--8<-- "examples/basic_json__basic_json.cpp"
#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:
```json
--8<-- "examples/basic_json__basic_json.output"
["one","two",3,4.5,false] = ["one","two",3,4.5,false]
true
```
??? example "Example: (9) move constructor"
@@ -452,13 +882,32 @@ basic_json(basic_json&& other) noexcept;
The code below shows the move constructor explicitly called via `std::move`.
```cpp
--8<-- "examples/basic_json__moveconstructor.cpp"
#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:
```json
--8<-- "examples/basic_json__moveconstructor.output"
null
23
```
## See also
File diff suppressed because one or more lines are too long
+19 -2
View File
@@ -28,13 +28,30 @@ Constant.
The following code shows an example for `begin()`.
```cpp
--8<-- "examples/begin.cpp"
#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:
```json
--8<-- "examples/begin.output"
1
```
## See also
File diff suppressed because one or more lines are too long
+19 -2
View File
@@ -52,13 +52,30 @@ initialization of a binary array type, for backwards compatibility and so it doe
The following code shows how to create a binary value.
```cpp
--8<-- "examples/binary.cpp"
#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:
```json
--8<-- "examples/binary.output"
type: binary, subtype: 42
```
## See also
File diff suppressed because one or more lines are too long
+13 -2
View File
@@ -106,13 +106,24 @@ type `#!cpp binary_t*` must be dereferenced.
`#!cpp nlohmann::byte_container_with_subtype<std::vector<std::uint8_t>>`.
```cpp
--8<-- "examples/binary_t.cpp"
#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:
```json
--8<-- "examples/binary_t.output"
true
```
## See also
File diff suppressed because one or more lines are too long
+13 -2
View File
@@ -36,13 +36,24 @@ Boolean values are stored directly inside a `basic_json` type.
The following code shows that `boolean_t` is by default, a typedef to `#!cpp bool`.
```cpp
--8<-- "examples/boolean_t.cpp"
#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:
```json
--8<-- "examples/boolean_t.output"
true
```
## See also
File diff suppressed because one or more lines are too long
+19 -2
View File
@@ -27,13 +27,30 @@ Constant.
The following code shows an example for `cbegin()`.
```cpp
--8<-- "examples/cbegin.cpp"
#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:
```json
--8<-- "examples/cbegin.output"
1
```
## See also
File diff suppressed because one or more lines are too long
+33 -2
View File
@@ -29,13 +29,44 @@ store
[`from_cbor`](from_cbor.md) when reading a tagged byte string.
```cpp
--8<-- "examples/cbor_tag_handler_t.cpp"
#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 (const 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
--8<-- "examples/cbor_tag_handler_t.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}
```
## See also
File diff suppressed because one or more lines are too long
+22 -2
View File
@@ -27,13 +27,33 @@ Constant.
The following code shows an example for `cend()`.
```cpp
--8<-- "examples/cend.cpp"
#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:
```json
--8<-- "examples/cend.output"
5
```
## See also
File diff suppressed because one or more lines are too long
+43 -2
View File
@@ -43,13 +43,54 @@ All iterators, pointers, and references related to this container are invalidate
JSON types.
```cpp
--8<-- "examples/clear.cpp"
#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:
```json
--8<-- "examples/clear.output"
null
false
0
0.0
{}
[]
""
```
## See also
File diff suppressed because one or more lines are too long
+95 -6
View File
@@ -10,6 +10,10 @@ bool contains(KeyType&& key) const;
// (3)
bool contains(const json_pointer& ptr) const;
// (4)
template<typename T>
bool contains(T) const = delete;
```
1. Check whether an element exists in a JSON object with a key equivalent to `key`. If the element is not found or the
@@ -17,6 +21,9 @@ bool contains(const json_pointer& ptr) const;
2. See 1. This overload is only available if `KeyType` is comparable with `#!cpp typename object_t::key_type` and
`#!cpp typename object_comparator_t::is_transparent` denotes a type.
3. Check whether the given JSON pointer `ptr` can be resolved in the current JSON value.
4. Deleted: this overload is only available if `T` is an integral type and is declared as deleted, so that a call with
an integer `key` (for example, `#!cpp j.contains(0)`) fails to compile. Otherwise, the integer literal `0` would convert to
a null `#!cpp const char*` and, from there, to the key type, causing undefined behavior at runtime.
## Template parameters
@@ -39,6 +46,7 @@ bool contains(const json_pointer& ptr) const;
is not an object, `#!cpp false` is returned.
2. See 1.
3. `#!cpp true` if the JSON pointer can be resolved to a stored value, `#!cpp false` otherwise.
4. Deleted; a call with an integral argument does not compile.
## Exception safety
@@ -49,6 +57,7 @@ Strong exception safety: if an exception occurs, the original value stays intact
1. The function does not throw exceptions.
2. The function does not throw exceptions.
3. The function does not throw exceptions.
4. Deleted; a call with an integral argument does not compile.
## Complexity
@@ -86,13 +95,34 @@ Logarithmic in the size of the JSON object.
The example shows how `contains()` is used.
```cpp
--8<-- "examples/contains__object_t_key_type.cpp"
#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:
```json
--8<-- "examples/contains__object_t_key_type.output"
j_object contains 'key': true
j_object contains 'another': false
j_array contains 'key': false
```
??? example "Example: (2) check with key using string_view"
@@ -100,13 +130,36 @@ Logarithmic in the size of the JSON object.
The example shows how `contains()` is used.
```cpp
--8<-- "examples/contains__keytype.c++17.cpp"
#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:
```json
--8<-- "examples/contains__keytype.c++17.output"
j_object contains 'key': true
j_object contains 'another': false
j_array contains 'key': false
```
??? example "Example: (3) check with JSON pointer"
@@ -114,13 +167,49 @@ Logarithmic in the size of the JSON object.
The example shows how `contains()` is used.
```cpp
--8<-- "examples/contains__json_pointer.cpp"
#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) << '\n'
// an array index with a leading '0' is not found
<< j.contains("/array/01"_json_pointer) << '\n'
// an array index that is not a number is not found
<< j.contains("/array/one"_json_pointer) << std::endl;
}
```
Output:
```json
--8<-- "examples/contains__json_pointer.output"
true
true
true
true
false
false
false
false
false
```
## See also
File diff suppressed because one or more lines are too long
+7
View File
@@ -10,11 +10,16 @@ bool contains(KeyType&& key) const;
// (3)
bool contains(const json_pointer& ptr) const;
// (4)
template<typename T>
bool contains(T) const = delete;
```
1. Check whether an element exists in a JSON object with a key equivalent to `key`. If the element is not found or the JSON value is not an object, `false` is returned.
1. 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.
1. Check whether the given JSON pointer `ptr` can be resolved in the current JSON value.
1. Deleted: this overload is only available if `T` is an integral type and is declared as deleted, so that a call with an integer `key` (for example, `j.contains(0)`) fails to compile. Otherwise, the integer literal `0` would convert to a null `const char*` and, from there, to the key type, causing undefined behavior at runtime.
## Template parameters
@@ -31,6 +36,7 @@ bool contains(const json_pointer& ptr) const;
1. `true` if an element with specified `key` exists. If no such element with such a key is found or the JSON value is not an object, `false` is returned.
1. See 1.
1. `true` if the JSON pointer can be resolved to a stored value, `false` otherwise.
1. Deleted; a call with an integral argument does not compile.
## Exception safety
@@ -41,6 +47,7 @@ Strong exception safety: if an exception occurs, the original value stays intact
1. The function does not throw exceptions.
1. The function does not throw exceptions.
1. The function does not throw exceptions.
1. Deleted; a call with an integral argument does not compile.
## Complexity
+53 -4
View File
@@ -7,12 +7,19 @@ size_type count(const typename object_t::key_type& key) const;
// (2)
template<typename KeyType>
size_type count(KeyType&& key) const;
// (3)
template<typename T>
size_type count(T) const = delete;
```
1. Returns the number of elements with key `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).
2. See 1. This overload is only available if `KeyType` is comparable with `#!cpp typename object_t::key_type` and
`#!cpp typename object_comparator_t::is_transparent` denotes a type.
3. Deleted: this overload is only available if `T` is an integral type and is declared as deleted, so that a call with
an integer `key` (for example, `#!cpp j.count(0)`) fails to compile. Otherwise, the integer literal `0` would convert to
a null `#!cpp const char*` and, from there, to the key type, causing undefined behavior at runtime.
## Template parameters
@@ -53,13 +60,33 @@ Logarithmic in the size of the JSON object.
The example shows how `count()` is used.
```cpp
--8<-- "examples/count__object_t_key_type.cpp"
#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:
```json
--8<-- "examples/count__object_t_key_type.output"
number of elements with key "two": 1
number of elements with key "three": 0
```
??? example "Example: (2) count number of elements using string_view"
@@ -67,13 +94,35 @@ Logarithmic in the size of the JSON object.
The example shows how `count()` is used.
```cpp
--8<-- "examples/count__keytype.c++17.cpp"
#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:
```json
--8<-- "examples/count__keytype.c++17.output"
number of elements with key "two": 1
number of elements with key "three": 0
```
## See also
File diff suppressed because one or more lines are too long
+5
View File
@@ -7,10 +7,15 @@ size_type count(const typename object_t::key_type& key) const;
// (2)
template<typename KeyType>
size_type count(KeyType&& key) const;
// (3)
template<typename T>
size_type count(T) const = delete;
```
1. Returns the number of elements with key `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).
1. 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.
1. Deleted: this overload is only available if `T` is an integral type and is declared as deleted, so that a call with an integer `key` (for example, `j.count(0)`) fails to compile. Otherwise, the integer literal `0` would convert to a null `const char*` and, from there, to the key type, causing undefined behavior at runtime.
## Template parameters
+19 -2
View File
@@ -27,13 +27,30 @@ Constant.
The following code shows an example for `crbegin()`.
```cpp
--8<-- "examples/crbegin.cpp"
#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:
```json
--8<-- "examples/crbegin.output"
5
```
## See also
File diff suppressed because one or more lines are too long
+22 -2
View File
@@ -28,13 +28,33 @@ Constant.
The following code shows an example for `crend()`.
```cpp
--8<-- "examples/crend.cpp"
#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:
```json
--8<-- "examples/crend.output"
1
```
## See also
File diff suppressed because one or more lines are too long
+15 -2
View File
@@ -21,13 +21,26 @@ The actual comparator used depends on [`object_t`](object_t.md) and can be obtai
The example below demonstrates the default comparator.
```cpp
--8<-- "examples/default_object_comparator_t.cpp"
#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:
```json
--8<-- "examples/default_object_comparator_t.output"
one < two : true
three < four : false
```
## See also
File diff suppressed because one or more lines are too long
+65 -2
View File
@@ -44,13 +44,75 @@ 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.
```cpp
--8<-- "examples/diff.cpp"
#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:
```json
--8<-- "examples/diff.output"
[
{
"op": "replace",
"path": "/baz",
"value": "boo"
},
{
"op": "remove",
"path": "/foo"
},
{
"op": "add",
"path": "/hello",
"value": [
"world"
]
}
]
{
"baz": "boo",
"hello": [
"world"
]
}
```
## See also
@@ -59,6 +121,7 @@ Currently, only `remove`, `add`, and `replace` operations are generated.
- [patch](patch.md) applies a JSON Patch
- [patch_inplace](patch_inplace.md) applies a JSON Patch in place
- [merge_patch](merge_patch.md) applies a JSON Merge Patch
- [merge_diff](merge_diff.md) creates a diff as a JSON Merge Patch
## Version history
File diff suppressed because one or more lines are too long
+1
View File
@@ -117,6 +117,7 @@ Output:
- [patch](https://json.nlohmann.me/api/basic_json/patch/index.md) applies a JSON Patch
- [patch_inplace](https://json.nlohmann.me/api/basic_json/patch_inplace/index.md) applies a JSON Patch in place
- [merge_patch](https://json.nlohmann.me/api/basic_json/merge_patch/index.md) applies a JSON Merge Patch
- [merge_diff](https://json.nlohmann.me/api/basic_json/merge_diff/index.md) creates a diff as a JSON Merge Patch
## Version history
+105 -2
View File
@@ -75,13 +75,116 @@ Binary values are serialized as an object containing two keys:
result of the serialization.
```cpp
--8<-- "examples/dump.cpp"
#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 (const 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
--8<-- "examples/dump.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: "äü"
```
## See also
File diff suppressed because one or more lines are too long
+39 -2
View File
@@ -52,13 +52,50 @@ Logarithmic in the size of the container, O(log(`size()`)).
the same key.
```cpp
--8<-- "examples/emplace.cpp"
#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:
```json
--8<-- "examples/emplace.output"
{"one":1,"two":2}
null
{"one":1,"three":3,"two":2}
3 true
{"A":"a","B":"b"}
"b" false
```
## See also
File diff suppressed because one or more lines are too long
+30 -2
View File
@@ -50,13 +50,41 @@ Amortized constant.
silently converted to a JSON array.
```cpp
--8<-- "examples/emplace_back.cpp"
#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:
```json
--8<-- "examples/emplace_back.output"
[1,2,3,4,5]
null
[1,2,3,4,5,6]
["first",["second","second","second"]]
```
## See also
File diff suppressed because one or more lines are too long
+41 -2
View File
@@ -51,13 +51,52 @@ itself is empty which is `#!cpp false` in the case of a string.
The following code uses `empty()` to check if a JSON object contains any elements.
```cpp
--8<-- "examples/empty.cpp"
#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:
```json
--8<-- "examples/empty.output"
true
false
false
false
false
true
false
true
false
```
## See also
File diff suppressed because one or more lines are too long
+22 -2
View File
@@ -28,13 +28,33 @@ Constant.
The following code shows an example for `end()`.
```cpp
--8<-- "examples/end.cpp"
#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:
```json
--8<-- "examples/end.output"
5
```
## See also
File diff suppressed because one or more lines are too long
+103 -2
View File
@@ -47,13 +47,114 @@ Constant.
??? example "Example"
```cpp
--8<-- "examples/diagnostic_positions.cpp"
#include <iostream>
#define JSON_DIAGNOSTIC_POSITIONS 1
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
std::string json_string = R"(
{
"address": {
"street": "Fake Street",
"housenumber": 1
}
}
)";
json j = json::parse(json_string);
std::cout << "Root diagnostic positions: \n";
std::cout << "\tstart_pos: " << j.start_pos() << '\n';
std::cout << "\tend_pos:" << j.end_pos() << "\n";
std::cout << "Original string: \n";
std::cout << "{\n \"address\": {\n \"street\": \"Fake Street\",\n \"housenumber\": 1\n }\n }" << "\n";
std::cout << "Parsed string: \n";
std::cout << json_string.substr(j.start_pos(), j.end_pos() - j.start_pos()) << "\n\n";
std::cout << "address diagnostic positions: \n";
std::cout << "\tstart_pos:" << j["address"].start_pos() << '\n';
std::cout << "\tend_pos:" << j["address"].end_pos() << "\n\n";
std::cout << "Original string: \n";
std::cout << "{ \"street\": \"Fake Street\",\n \"housenumber\": 1\n }" << "\n";
std::cout << "Parsed string: \n";
std::cout << json_string.substr(j["address"].start_pos(), j["address"].end_pos() - j["address"].start_pos()) << "\n\n";
std::cout << "street diagnostic positions: \n";
std::cout << "\tstart_pos:" << j["address"]["street"].start_pos() << '\n';
std::cout << "\tend_pos:" << j["address"]["street"].end_pos() << "\n\n";
std::cout << "Original string: \n";
std::cout << "\"Fake Street\"" << "\n";
std::cout << "Parsed string: \n";
std::cout << json_string.substr(j["address"]["street"].start_pos(), j["address"]["street"].end_pos() - j["address"]["street"].start_pos()) << "\n\n";
std::cout << "housenumber diagnostic positions: \n";
std::cout << "\tstart_pos:" << j["address"]["housenumber"].start_pos() << '\n';
std::cout << "\tend_pos:" << j["address"]["housenumber"].end_pos() << "\n\n";
std::cout << "Original string: \n";
std::cout << "1" << "\n";
std::cout << "Parsed string: \n";
std::cout << json_string.substr(j["address"]["housenumber"].start_pos(), j["address"]["housenumber"].end_pos() - j["address"]["housenumber"].start_pos()) << "\n\n";
}
```
Output:
```
--8<-- "examples/diagnostic_positions.output"
Root diagnostic positions:
start_pos: 5
end_pos:109
Original string:
{
"address": {
"street": "Fake Street",
"housenumber": 1
}
}
Parsed string:
{
"address": {
"street": "Fake Street",
"housenumber": 1
}
}
address diagnostic positions:
start_pos:26
end_pos:103
Original string:
{ "street": "Fake Street",
"housenumber": 1
}
Parsed string:
{
"street": "Fake Street",
"housenumber": 1
}
street diagnostic positions:
start_pos:50
end_pos:63
Original string:
"Fake Street"
Parsed string:
"Fake Street"
housenumber diagnostic positions:
start_pos:92
end_pos:93
Original string:
1
Parsed string:
1
```
The output shows the start/end positions of all the objects and fields in the JSON string.
File diff suppressed because one or more lines are too long
+143 -10
View File
@@ -137,13 +137,50 @@ Strong exception safety: if an exception occurs, the original value stays intact
The example shows the effect of `erase()` for different JSON types using an iterator.
```cpp
--8<-- "examples/erase__IteratorType.cpp"
#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:
```json
--8<-- "examples/erase__IteratorType.output"
null
null
null
{"one":1}
[1,2,8,16]
null
```
??? example "Example: (2) remove elements given an iterator range"
@@ -151,13 +188,50 @@ Strong exception safety: if an exception occurs, the original value stays intact
The example shows the effect of `erase()` for different JSON types using an iterator range.
```cpp
--8<-- "examples/erase__IteratorType_IteratorType.cpp"
#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:
```json
--8<-- "examples/erase__IteratorType_IteratorType.output"
null
null
null
{"one":1}
[1,8,16]
null
```
??? example "Example: (3) remove element from a JSON object given a key"
@@ -165,13 +239,33 @@ Strong exception safety: if an exception occurs, the original value stays intact
The example shows the effect of `erase()` for different JSON types using an object key.
```cpp
--8<-- "examples/erase__object_t_key_type.cpp"
#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:
```json
--8<-- "examples/erase__object_t_key_type.output"
{"two":2}
1 0
```
??? example "Example: (4) remove element from a JSON object given a key using string_view"
@@ -179,13 +273,35 @@ Strong exception safety: if an exception occurs, the original value stays intact
The example shows the effect of `erase()` for different JSON types using an object key.
```cpp
--8<-- "examples/erase__keytype.c++17.cpp"
#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:
```json
--8<-- "examples/erase__keytype.c++17.output"
{"two":2}
1 0
```
??? example "Example: (5) remove element from a JSON array given an index"
@@ -193,13 +309,30 @@ Strong exception safety: if an exception occurs, the original value stays intact
The example shows the effect of `erase()` using an array index.
```cpp
--8<-- "examples/erase__size_type.cpp"
#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:
```json
--8<-- "examples/erase__size_type.output"
[0,1,3,4,5]
```
## See also
File diff suppressed because one or more lines are too long
+33 -4
View File
@@ -37,8 +37,8 @@ ignore
: ignore invalid UTF-8 sequences; all valid bytes are copied to the output unchanged, and invalid bytes are dropped
keep
: keep invalid UTF-8 sequences unchanged; only meaningful for the binary formats mentioned above, since [`dump`]
(dump.md) itself must produce text, and `keep` there writes the ill-formed bytes to the output as is, so the
: keep invalid UTF-8 sequences unchanged; only meaningful for the binary formats mentioned above, since
[`dump`](dump.md) itself must produce text, and `keep` there writes the ill-formed bytes to the output as is, so the
result is then not valid UTF-8 (but still equals the input bytes exactly, including around any well-formed
characters, which are still escaped as usual)
@@ -50,13 +50,42 @@ keep
[`dump`](dump.md) when reading serializing an invalid UTF-8 sequence.
```cpp
--8<-- "examples/error_handler_t.cpp"
#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 (const 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)
<< "\nstring with the invalid byte kept as is (" << j_invalid.dump(-1, ' ', false, json::error_handler_t::keep).size()
<< " bytes, not valid UTF-8 itself)\n";
}
```
Output:
```json
--8<-- "examples/error_handler_t.output"
[json.exception.type_error.316] invalid UTF-8 byte at index 2: 0xA9
string with replaced invalid characters: "ä�ü"
string with ignored invalid characters: "äü"
string with the invalid byte kept as is (7 bytes, not valid UTF-8 itself)
```
## See also
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -23,7 +23,7 @@ replace : replace invalid UTF-8 sequences with U+FFFD (� REPLACEMENT CHARACTER
ignore : ignore invalid UTF-8 sequences; all valid bytes are copied to the output unchanged, and invalid bytes are dropped
keep : keep invalid UTF-8 sequences unchanged; only meaningful for the binary formats mentioned above, since \[`dump`\] (dump.md) itself must produce text, and `keep` there writes the ill-formed bytes to the output as is, so the result is then not valid UTF-8 (but still equals the input bytes exactly, including around any well-formed characters, which are still escaped as usual)
keep : keep invalid UTF-8 sequences unchanged; only meaningful for the binary formats mentioned above, since [`dump`](https://json.nlohmann.me/api/basic_json/dump/index.md) itself must produce text, and `keep` there writes the ill-formed bytes to the output as is, so the result is then not valid UTF-8 (but still equals the input bytes exactly, including around any well-formed characters, which are still escaped as usual)
## Examples
+24 -2
View File
@@ -69,13 +69,35 @@ constructor.
The following code shows how arbitrary library exceptions can be caught.
```cpp
--8<-- "examples/exception.cpp"
#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 (const json::exception& e)
{
// output exception information
std::cout << "message: " << e.what() << '\n'
<< "exception id: " << e.id << std::endl;
}
}
```
Output:
```json
--8<-- "examples/exception.output"
message: [json.exception.out_of_range.403] key 'non-existing' not found
exception id: 403
```
## See also
File diff suppressed because one or more lines are too long
+61 -4
View File
@@ -10,12 +10,21 @@ template<typename KeyType>
iterator find(KeyType&& key);
template<typename KeyType>
const_iterator find(KeyType&& key) const;
// (3)
template<typename T>
iterator find(T) = delete;
template<typename T>
const_iterator find(T) const = delete;
```
1. Finds an element in a JSON object with a key equivalent to `key`. If the element is not found or the
JSON value is not an object, `end()` is returned.
2. See 1. This overload is only available if `KeyType` is comparable with `#!cpp typename object_t::key_type` and
`#!cpp typename object_comparator_t::is_transparent` denotes a type.
3. Deleted: this overload is only available if `T` is an integral type and is declared as deleted, so that a call with
an integer `key` (for example, `#!cpp j.find(0)`) fails to compile. Otherwise, the integer literal `0` would convert to
a null `#!cpp const char*` and, from there, to the key type, causing undefined behavior at runtime.
## Template parameters
@@ -57,13 +66,36 @@ Logarithmic in the size of the JSON object.
The example shows how `find()` is used.
```cpp
--8<-- "examples/find__object_t_key_type.cpp"
#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:
```json
--8<-- "examples/find__object_t_key_type.output"
"two" was found: true
value at key "two": 2
"three" was found: false
```
??? example "Example: (2) find object element by key using string_view"
@@ -71,13 +103,38 @@ Logarithmic in the size of the JSON object.
The example shows how `find()` is used.
```cpp
--8<-- "examples/find__keytype.c++17.cpp"
#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:
```json
--8<-- "examples/find__keytype.c++17.output"
"two" was found: true
value at key "two": 2
"three" was found: false
```
## See also
File diff suppressed because one or more lines are too long
+7
View File
@@ -10,10 +10,17 @@ template<typename KeyType>
iterator find(KeyType&& key);
template<typename KeyType>
const_iterator find(KeyType&& key) const;
// (3)
template<typename T>
iterator find(T) = delete;
template<typename T>
const_iterator find(T) const = delete;
```
1. Finds an element in a JSON object with a key equivalent to `key`. If the element is not found or the JSON value is not an object, `end()` is returned.
1. 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.
1. Deleted: this overload is only available if `T` is an integral type and is declared as deleted, so that a call with an integer `key` (for example, `j.find(0)`) fails to compile. Otherwise, the integer literal `0` would convert to a null `const char*` and, from there, to the key type, causing undefined behavior at runtime.
## Template parameters
+82 -4
View File
@@ -32,13 +32,57 @@ Empty objects and arrays are flattened to `#!json null` and will not be reconstr
The following code shows how a JSON object is flattened to an object whose keys consist of JSON pointers.
```cpp
--8<-- "examples/flatten.cpp"
#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:
```json
--8<-- "examples/flatten.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
}
```
??? example "Example: empty objects and arrays are flattened to `#!json null`"
@@ -47,13 +91,47 @@ Empty objects and arrays are flattened to `#!json null` and will not be reconstr
`unflatten()` restores them as `#!json null` rather than as empty containers.
```cpp
--8<-- "examples/flatten__empty.cpp"
#include <iostream>
#include <iomanip>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
// create a JSON value with an empty object and an empty array
json j =
{
{"empty_object", json::object()},
{"empty_array", json::array()},
{"name", "Niels"}
};
// call flatten()
json flattened = j.flatten();
std::cout << std::setw(4) << flattened << "\n\n";
// the empty containers cannot be restored by unflatten()
std::cout << std::setw(4) << flattened.unflatten() << '\n';
}
```
Output:
```json
--8<-- "examples/flatten__empty.output"
{
"/empty_array": null,
"/empty_object": null,
"/name": "Niels"
}
{
"empty_array": null,
"empty_object": null,
"name": "Niels"
}
```
## See also
File diff suppressed because one or more lines are too long
+81 -3
View File
@@ -57,7 +57,68 @@ std::string format_as(const BasicJsonType& j)
`#!cpp "{:.>#}"`), define your own `fmt::formatter` specialization mirroring the same logic:
```cpp
--8<-- "../../../tests/fmt_formatter/project/main.cpp:formatter_recipe"
template <>
struct fmt::formatter<nlohmann::json>
{
// -1 means compact output (dump()); any value >= 0 means pretty-printed
// output with that many spaces (or indent_char) per level.
int indent = -1;
char indent_char = ' ';
constexpr auto parse(format_parse_context& ctx) -> format_parse_context::iterator
{
auto it = ctx.begin();
const auto end = ctx.end();
constexpr auto is_align = [](char c)
{
return c == '<' || c == '>' || c == '^';
};
// [[fill] align] - repurposed here to pick a custom indent character
if (it != end && it + 1 != end && is_align(it[1]))
{
indent_char = *it;
it += 2;
}
else if (it != end && is_align(*it))
{
++it;
}
// ['#'] - "alternate form", used here to request pretty-printing with a
// default indent of 4 (overridden by an explicit width below, if given)
if (it != end && *it == '#')
{
indent = 4;
++it;
}
// [width] - repurposed here to pick the indent size; a width without '#'
// implies pretty-printing since an indent otherwise has no meaning
if (it != end && *it >= '1' && *it <= '9')
{
indent = 0;
while (it != end && *it >= '0' && *it <= '9')
{
indent = (indent * 10) + (*it - '0');
++it;
}
}
if (it != end && *it != '}')
{
throw fmt::format_error("invalid format args for nlohmann::json");
}
return it;
}
auto format(const nlohmann::json& j, format_context& ctx) const
{
const auto dumped = j.dump(indent, indent_char);
return fmt::format_to(ctx.out(), "{}", dumped);
}
};
```
This recipe isn't shipped by the library itself, since doing so would make `fmt` a build dependency
@@ -75,13 +136,30 @@ std::string format_as(const BasicJsonType& j)
allowing argument-dependent lookup.
```cpp
--8<-- "examples/format_as.cpp"
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
// create a JSON value
json j = {{"one", 1}, {"two", 2}};
// format_as() is found via argument-dependent lookup, the same way
// fmt::format/fmt::print would find it
auto j_str = format_as(j);
std::cout << j_str << std::endl;
}
```
Output:
```json
--8<-- "examples/format_as.output"
{"one":1,"two":2}
```
## See also
File diff suppressed because one or more lines are too long
+28 -3
View File
@@ -96,13 +96,37 @@ Linear in the size of the input.
The example shows the deserialization of a byte vector in BJData format to a JSON value.
```cpp
--8<-- "examples/from_bjdata.cpp"
#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:
```json
--8<-- "examples/from_bjdata.output"
{
"compact": true,
"schema": 0
}
```
## See also
@@ -124,7 +148,8 @@ Linear in the size of the input.
!!! warning "Deprecation"
- Overload (2) replaces calls to `from_bjdata` with a pointer and a length as first two parameters, which has been
deprecated in version 3.13.0. This overload will be removed in version 4.0.0. Please replace all calls like
deprecated in version 3.13.0. In version 4.0.0, this overload
will be deleted (`= delete`) rather than removed. Please replace all calls like
`#!cpp from_bjdata(ptr, len, ...);` with `#!cpp from_bjdata(ptr, ptr+len, ...);`.
You should be warned by your compiler with a `-Wdeprecated-declarations` warning if you are using a deprecated
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -133,6 +133,6 @@ Output:
Deprecation
- Overload (2) replaces calls to `from_bjdata` with a pointer and a length as first two parameters, which has been deprecated in version 3.13.0 unreleased. This overload will be removed in version 4.0.0. Please replace all calls like `from_bjdata(ptr, len, ...);` with `from_bjdata(ptr, ptr+len, ...);`.
- Overload (2) replaces calls to `from_bjdata` with a pointer and a length as first two parameters, which has been deprecated in version 3.13.0 unreleased. In version 4.0.0 unreleased, this overload will be deleted (`= delete`) rather than removed. Please replace all calls like `from_bjdata(ptr, len, ...);` with `from_bjdata(ptr, ptr+len, ...);`.
You should be warned by your compiler with a `-Wdeprecated-declarations` warning if you are using a deprecated function.
+30 -3
View File
@@ -85,13 +85,39 @@ Linear in the size of the input.
The example shows the deserialization of a byte vector in BON8 format to a JSON value.
```cpp
--8<-- "examples/from_bon8.cpp"
#include <iostream>
#include <iomanip>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
// create byte vector
std::vector<std::uint8_t> v = {0x89, 0x63, 0x6f, 0x6d, 0x70, 0x61, 0x63, 0x74,
0xf9, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0xff,
0x42, 0x4f, 0x4e, 0x38, 0xff, 0x73, 0x63, 0x68,
0x65, 0x6d, 0x61, 0x90
};
// deserialize it with BON8
json j = json::from_bon8(v);
// print the deserialized JSON value
std::cout << std::setw(2) << j << std::endl;
}
```
Output:
```json
--8<-- "examples/from_bon8.output"
{
"compact": true,
"format": "BON8",
"schema": 0
}
```
## See also
@@ -110,7 +136,8 @@ Linear in the size of the input.
!!! warning "Deprecation"
- Overload (2) replaces calls to `from_bon8` with a pointer and a length as first two parameters, which has been
deprecated in version 3.13.0. This overload will be removed in version 4.0.0. Please replace all calls like
deprecated in version 3.13.0. In version 4.0.0, this overload
will be deleted (`= delete`) rather than removed. Please replace all calls like
`#!cpp from_bon8(ptr, len, ...);` with `#!cpp from_bon8(ptr, ptr+len, ...);`.
You should be warned by your compiler with a `-Wdeprecated-declarations` warning if you are using a deprecated
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -126,6 +126,6 @@ Output:
Deprecation
- Overload (2) replaces calls to `from_bon8` with a pointer and a length as first two parameters, which has been deprecated in version 3.13.0 unreleased. This overload will be removed in version 4.0.0. Please replace all calls like `from_bon8(ptr, len, ...);` with `from_bon8(ptr, ptr+len, ...);`.
- Overload (2) replaces calls to `from_bon8` with a pointer and a length as first two parameters, which has been deprecated in version 3.13.0 unreleased. In version 4.0.0 unreleased, this overload will be deleted (`= delete`) rather than removed. Please replace all calls like `from_bon8(ptr, len, ...);` with `from_bon8(ptr, ptr+len, ...);`.
You should be warned by your compiler with a `-Wdeprecated-declarations` warning if you are using a deprecated function.
+29 -3
View File
@@ -97,13 +97,38 @@ Linear in the size of the input.
The example shows the deserialization of a byte vector in BSON format to a JSON value.
```cpp
--8<-- "examples/from_bson.cpp"
#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:
```json
--8<-- "examples/from_bson.output"
{
"compact": true,
"schema": 0
}
```
## See also
@@ -126,7 +151,8 @@ Linear in the size of the input.
!!! warning "Deprecation"
- Overload (2) replaces calls to `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
deprecated in version 3.8.0. In version 4.0.0, this overload
will be deleted (`= delete`) rather than removed. Please replace all calls like
`#!cpp from_bson(ptr, len, ...);` with `#!cpp from_bson(ptr, ptr+len, ...);`.
- Overload (2) replaces calls to `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
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -135,7 +135,7 @@ Output:
Deprecation
- Overload (2) replaces calls to `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, ...);`.
- Overload (2) replaces calls to `from_bson` with a pointer and a length as first two parameters, which has been deprecated in version 3.8.0. In version 4.0.0 unreleased, this overload will be deleted (`= delete`) rather than removed. Please replace all calls like `from_bson(ptr, len, ...);` with `from_bson(ptr, ptr+len, ...);`.
- Overload (2) replaces calls to `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.
+28 -3
View File
@@ -103,13 +103,37 @@ Linear in the size of the input.
The example shows the deserialization of a byte vector in CBOR format to a JSON value.
```cpp
--8<-- "examples/from_cbor.cpp"
#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:
```json
--8<-- "examples/from_cbor.output"
{
"compact": true,
"schema": 0
}
```
## See also
@@ -135,7 +159,8 @@ Linear in the size of the input.
!!! warning "Deprecation"
- Overload (2) replaces calls to `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
deprecated in version 3.8.0. In version 4.0.0, this overload
will be deleted (`= delete`) rather than removed. Please replace all calls like
`#!cpp from_cbor(ptr, len, ...);` with `#!cpp from_cbor(ptr, ptr+len, ...);`.
- Overload (2) replaces calls to `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
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -141,7 +141,7 @@ Output:
Deprecation
- Overload (2) replaces calls to `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, ...);`.
- Overload (2) replaces calls to `from_cbor` with a pointer and a length as first two parameters, which has been deprecated in version 3.8.0. In version 4.0.0 unreleased, this overload will be deleted (`= delete`) rather than removed. Please replace all calls like `from_cbor(ptr, len, ...);` with `from_cbor(ptr, ptr+len, ...);`.
- Overload (2) replaces calls to `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.
+28 -3
View File
@@ -96,13 +96,37 @@ Linear in the size of the input.
The example shows the deserialization of a byte vector in MessagePack format to a JSON value.
```cpp
--8<-- "examples/from_msgpack.cpp"
#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:
```json
--8<-- "examples/from_msgpack.output"
{
"compact": true,
"schema": 0
}
```
## See also
@@ -127,7 +151,8 @@ Linear in the size of the input.
!!! warning "Deprecation"
- Overload (2) replaces calls to `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
deprecated in version 3.8.0. In version 4.0.0, this overload
will be deleted (`= delete`) rather than removed. Please replace all calls like
`#!cpp from_msgpack(ptr, len, ...);` with `#!cpp from_msgpack(ptr, ptr+len, ...);`.
- Overload (2) replaces calls to `from_msgpack` 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
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -135,7 +135,7 @@ Output:
Deprecation
- Overload (2) replaces calls to `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, ...);`.
- Overload (2) replaces calls to `from_msgpack` with a pointer and a length as first two parameters, which has been deprecated in version 3.8.0. In version 4.0.0 unreleased, this overload will be deleted (`= delete`) rather than removed. Please replace all calls like `from_msgpack(ptr, len, ...);` with `from_msgpack(ptr, ptr+len, ...);`.
- Overload (2) replaces calls to `from_msgpack` 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.
+28 -3
View File
@@ -96,13 +96,37 @@ Linear in the size of the input.
The example shows the deserialization of a byte vector in UBJSON format to a JSON value.
```cpp
--8<-- "examples/from_ubjson.cpp"
#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:
```json
--8<-- "examples/from_ubjson.output"
{
"compact": true,
"schema": 0
}
```
## See also
@@ -125,7 +149,8 @@ Linear in the size of the input.
!!! warning "Deprecation"
- Overload (2) replaces calls to `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
deprecated in version 3.8.0. In version 4.0.0, this overload
will be deleted (`= delete`) rather than removed. Please replace all calls like
`#!cpp from_ubjson(ptr, len, ...);` with `#!cpp from_ubjson(ptr, ptr+len, ...);`.
- Overload (2) replaces calls to `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
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -134,7 +134,7 @@ Output:
Deprecation
- Overload (2) replaces calls to `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, ...);`.
- Overload (2) replaces calls to `from_ubjson` with a pointer and a length as first two parameters, which has been deprecated in version 3.8.0. In version 4.0.0 unreleased, this overload will be deleted (`= delete`) rather than removed. Please replace all calls like `from_ubjson(ptr, len, ...);` with `from_ubjson(ptr, ptr+len, ...);`.
- Overload (2) replaces calls to `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.
+37 -2
View File
@@ -39,13 +39,48 @@ Constant.
The following code shows an example for `front()`.
```cpp
--8<-- "examples/front.cpp"
#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:
```json
--8<-- "examples/front.output"
true
17
23.42
1
1
"Hello, world"
```
## See also
File diff suppressed because one or more lines are too long
+109 -6
View File
@@ -138,13 +138,74 @@ overload (3).
associative containers such as `std::map<std::string, json>`.
```cpp
--8<-- "examples/get__ValueType_const.cpp"
#include <iostream>
#include <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::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:
```json
--8<-- "examples/get__ValueType_const.output"
1
42 42
17.23 17
Hello, world!
1 2 3 4 5
array: [1,2,3,4,5]
boolean: true
null: null
number: {"floating-point":17.23,"integer":42}
string: "Hello, world!"
```
??? example "Example: (2) explicit conversion to another `basic_json` specialization"
@@ -152,13 +213,32 @@ overload (3).
The example below shows how a `json` value is converted to an `ordered_json` value using `get<BasicJsonType>()`.
```cpp
--8<-- "examples/get__BasicJsonType.cpp"
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
using ordered_json = nlohmann::ordered_json;
int main()
{
// create a JSON value
json j = {{"one", 1}, {"two", 2}, {"three", 3}};
// convert to a different basic_json specialization
ordered_json oj = j.get<ordered_json>();
std::cout << j << '\n';
std::cout << oj << '\n';
}
```
Output:
```json
--8<-- "examples/get__BasicJsonType.output"
{"one":1,"three":3,"two":2}
{"one":1,"three":3,"two":2}
```
??? example "Example: (3) explicit pointer access to the stored value"
@@ -167,13 +247,36 @@ overload (3).
conversions are made and a `#cpp nullptr` is returned if the value and the requested pointer type does not match.
```cpp
--8<-- "examples/get__PointerType.cpp"
#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:
```json
--8<-- "examples/get__PointerType.output"
17 17 17 17
true
```
## See also

Some files were not shown because too many files have changed in this diff Show More