mirror of
https://github.com/nlohmann/json.git
synced 2026-10-04 13:40:33 +00:00
Document values and JSON pointers of json_view
- API pages for get, get_to, get_string, number_token, and value of basic_json_view; JSON pointer overloads of operator[], at, and contains; links both ways with the basic_json pages - the feature page describes which conversions copy nothing - the examples show when the view helps: strings without copies, numbers exactly as written, and paths into a large text Signed-off-by: Niels Lohmann <mail@nlohmann.me>
This commit is contained in:
@@ -0,0 +1,29 @@
|
||||
#include <iostream>
|
||||
#include <nlohmann/json_view.hpp>
|
||||
#include <string>
|
||||
|
||||
using json_document = nlohmann::json_document;
|
||||
using json_view = nlohmann::json_view;
|
||||
|
||||
int main()
|
||||
{
|
||||
json_document doc = json_document::parse(R"({"server": {"host": "localhost"}})");
|
||||
const json_view server = doc.root()["server"];
|
||||
|
||||
// "port" is missing -- value() returns the default instead of
|
||||
// throwing, so optional configuration fields never need their own
|
||||
// try/catch
|
||||
std::cout << server.value("host", std::string("0.0.0.0")) << '\n';
|
||||
std::cout << server.value("port", 8080) << '\n';
|
||||
|
||||
// a present but wrong-typed default still throws -- value() only
|
||||
// replaces "not found", not "wrong type", exactly as basic_json::value
|
||||
try
|
||||
{
|
||||
static_cast<void>(server.value("host", 0));
|
||||
}
|
||||
catch (const nlohmann::json::type_error& e)
|
||||
{
|
||||
std::cout << e.what() << '\n';
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user