* Docs: fill documentation gaps found in user questions Add pages on class-hierarchy/smart-pointer/variant/chrono recipes, working without exceptions, and large, streamed and partial input. Extend the FAQ (23 entries, Known bugs first), parse error documentation (empty-input checklist, line/column, diagnostic positions), element access, conversions, creating values, ADL troubleshooting, memory, and build/distribution notes. Add 14 examples with generated output. Correct the statement that parse errors cannot be recovered from with -fno-exceptions. The topics come from recurring questions on Stack Overflow, Reddit, Hacker News, YouTube, and the project's GitHub discussions and issues. Signed-off-by: Niels Lohmann <mail@nlohmann.me> * docs: declare range-for lists in variables to keep astyle quiet astyle reformats a braced init list placed directly in a range-for header; declare the list first so check_amalgamation passes. Signed-off-by: Niels Lohmann <mail@nlohmann.me> --------- Signed-off-by: Niels Lohmann <mail@nlohmann.me>
44 lines
1.2 KiB
C++
44 lines
1.2 KiB
C++
#include <iostream>
|
|
#include <nlohmann/json.hpp>
|
|
|
|
using json = nlohmann::json;
|
|
|
|
int main()
|
|
{
|
|
json j = json::parse(R"({"name": "Mary", "age": 42})");
|
|
|
|
// look up the key, then test the type: neither step throws
|
|
const auto keys = {"name", "age", "city"};
|
|
for (const char* key : keys)
|
|
{
|
|
const auto it = j.find(key);
|
|
if (it == j.end())
|
|
{
|
|
std::cout << key << ": missing\n";
|
|
}
|
|
else if (it->is_string())
|
|
{
|
|
std::cout << key << ": string \"" << it->get_ref<const std::string&>() << "\"\n";
|
|
}
|
|
else
|
|
{
|
|
std::cout << key << ": not a string, but " << it->type_name() << '\n';
|
|
}
|
|
}
|
|
|
|
// get_ptr returns a null pointer if the value has another type
|
|
const std::string* name = j["name"].get_ptr<const std::string*>();
|
|
const std::string* age = j["age"].get_ptr<const std::string*>();
|
|
std::cout << "get_ptr<string*>: name = " << (name != nullptr) << ", age = " << (age != nullptr) << '\n';
|
|
|
|
// value() is NOT exception-free: it throws if the key exists with a different type
|
|
try
|
|
{
|
|
std::cout << j.value("name", 0) << '\n';
|
|
}
|
|
catch (const json::type_error& e)
|
|
{
|
|
std::cout << e.what() << '\n';
|
|
}
|
|
}
|