deploy: 94fe31eb9b
This commit is contained in:
1 parent
41c601a7d1
commit
d2e264bd84
1400 files changed
+11859
-5440
No files matched your search
@@ -27,7 +27,7 @@ Example
|
||||
#include <map>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
using json = nlohmann::json;
|
||||
using nlohmann::json;
|
||||
|
||||
int main()
|
||||
{
|
||||
@@ -77,7 +77,7 @@ int main()
|
||||
}
|
||||
std::cout << "\n\n";
|
||||
|
||||
for (auto i : v8)
|
||||
for (const auto& i : v8)
|
||||
{
|
||||
std::cout << i.first << ": " << i.second << '\n';
|
||||
}
|
||||
@@ -157,6 +157,24 @@ std::string s = j; // implicit conversion, same as j.get<std::string>()
|
||||
|
||||
Implicit conversions are convenient but can be surprising (for example, in overload resolution or with `auto`). They can be disabled by defining [`JSON_USE_IMPLICIT_CONVERSIONS`](https://json.nlohmann.me/api/macros/json_use_implicit_conversions/index.md) to `0`, which forces the explicit `get` form and can catch unintended conversions at compile time.
|
||||
|
||||
`auto` copies the JSON value; it does not convert it
|
||||
|
||||
The type of `j["name"]` is `json`, not the C++ type of the value inside. `auto` therefore deduces `json`:
|
||||
|
||||
```
|
||||
json j = {{"name", "Mary"}, {"age", 42}};
|
||||
|
||||
auto name = j["name"]; // json: a copy of the value; prints as "Mary" (with quotes)
|
||||
std::string s1 = j["name"]; // std::string: implicit conversion
|
||||
auto s2 = j["name"].get<std::string>(); // std::string: explicit conversion
|
||||
auto& age = j["age"]; // json&: a reference, no copy
|
||||
age = 43; // changes j
|
||||
```
|
||||
|
||||
This is also why `std::cout << j["name"]` prints the quotes (see [getting a string without quotes](#getting-values-out)), and why a `json` value cannot be passed to `printf`: the argument is not an `int` or a `char*`, and a compiler either rejects passing it through `...` (Clang does) or compiles it and prints garbage. Convert first: `std::printf("%d", j["age"].get<int>());`.
|
||||
|
||||
Prefer `get<T>()` over `auto` when you want the C++ value, and `auto&` or `const auto&` when you want to avoid a copy of a large value.
|
||||
|
||||
Conversions do not range-check numbers
|
||||
|
||||
Just like C++ itself, the `get` family performs numeric conversions without range checks — retrieving a floating-point value as an integer truncates it, and narrowing conversions may overflow. See [number conversion](https://json.nlohmann.me/features/types/number_handling/#number-conversion) for details and how to guard against it.
|
||||
|
||||
Reference in new issue
Block a user