Files
json/docs/mkdocs/docs/examples/basic_json_view__at.cpp
T
Niels Lohmann 08dcdaf9b8 Document element access, lookup, and iteration of json_view
- API pages for operator[], at, front, back, find, contains, count,
  begin, end, cbegin, cend, items, and type_name of basic_json_view,
  linked both ways with the basic_json pages
- the feature page and size() describe document order and duplicate
  keys
- the examples show when the view helps: reading a few fields of a large
  text, probing optional members, and members in source order

Signed-off-by: Niels Lohmann <mail@nlohmann.me>
2026-09-30 21:01:33 +02:00

37 lines
1.0 KiB
C++

#include <iostream>
#include <nlohmann/json_view.hpp>
using json_document = nlohmann::json_document;
using json_view = nlohmann::json_view;
int main()
{
// required fields of a service configuration -- at() reports a missing
// or wrong-typed field with the very same exception basic_json::at()
// would throw for the equivalent nlohmann::json value, so error
// handling written against basic_json::at() keeps working unchanged
json_document config = json_document::parse(R"({"name": "cache", "port": "6379"})");
const json_view service = config.root();
std::cout << service.at("port").materialize().dump() << '\n';
try
{
// "port" is a string, not an array
static_cast<void>(service.at("port").at(0));
}
catch (const nlohmann::json::type_error& e)
{
std::cout << e.what() << '\n';
}
try
{
static_cast<void>(service.at("timeout"));
}
catch (const nlohmann::json::out_of_range& e)
{
std::cout << e.what() << '\n';
}
}