mirror of
https://github.com/nlohmann/json.git
synced 2026-10-02 20:50:32 +00:00
- 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>
30 lines
880 B
C++
30 lines
880 B
C++
#include <iostream>
|
|
#include <nlohmann/json_view.hpp>
|
|
|
|
using json_document = nlohmann::json_document;
|
|
|
|
int main()
|
|
{
|
|
// validate that every transaction of a batch carries a mandatory
|
|
// "amount" field before materializing any of them into a nlohmann::json
|
|
// value -- count() returns 0 or 1 for an object
|
|
json_document batch = json_document::parse(R"(
|
|
[
|
|
{"id": 1, "amount": 9.99},
|
|
{"id": 2}
|
|
]
|
|
)");
|
|
|
|
const auto transactions = batch.root();
|
|
for (std::size_t i = 0; i < transactions.size(); ++i)
|
|
{
|
|
const auto transaction = transactions[i];
|
|
if (transaction.count("amount") == 0)
|
|
{
|
|
std::cout << "transaction " << i << " is missing \"amount\"\n";
|
|
continue;
|
|
}
|
|
std::cout << "transaction " << i << ": " << transaction["amount"].materialize().dump() << '\n';
|
|
}
|
|
}
|