Files
json/docs/mkdocs/docs/examples/basic_json_view__find.cpp
Niels Lohmann 2f087c6b73 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 15:08:00 +02:00

30 lines
829 B
C++

#include <iostream>
#include <nlohmann/json_view.hpp>
using json_document = nlohmann::json_document;
int main()
{
// a batch of incoming events; only some carry a "user_id" -- find()
// locates it without throwing for the events that turn out to not be
// objects, and without materializing an event that does not match
json_document batch = json_document::parse(R"(
[
{"type": "click", "user_id": 42},
{"type": "ping"},
{"type": "click", "user_id": 7}
]
)");
const auto events = batch.root();
for (std::size_t i = 0; i < events.size(); ++i)
{
const auto event = events[i];
const auto it = event.find("user_id");
if (it != event.end())
{
std::cout << "user " << it->materialize().dump() << '\n';
}
}
}