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:
Niels Lohmann
2026-09-30 21:01:37 +02:00
parent 0650a48659
commit 43e2d9c525
34 changed files with 1007 additions and 16 deletions
@@ -0,0 +1,34 @@
#include <iostream>
#include <nlohmann/json_view.hpp>
using json_document = nlohmann::json_document;
using json_pointer = nlohmann::json::json_pointer;
int main()
{
json_document doc = json_document::parse(R"({"region": "eu", "servers": ["eu-1", "eu-2"]})");
const auto root = doc.root();
std::cout << root.at(json_pointer("/servers/1")).materialize().dump() << '\n';
// at() throws for every resolution failure -- with the very same
// message json::at(ptr) would throw for the same pointer and the same
// document
try
{
static_cast<void>(root.at(json_pointer("/servers/5")));
}
catch (const nlohmann::json::out_of_range& e)
{
std::cout << e.what() << '\n';
}
try
{
static_cast<void>(root.at(json_pointer("/missing")));
}
catch (const nlohmann::json::out_of_range& e)
{
std::cout << e.what() << '\n';
}
}
@@ -0,0 +1,3 @@
"eu-2"
[json.exception.out_of_range.401] array index 5 is out of range
[json.exception.out_of_range.403] key 'missing' not found
@@ -0,0 +1,39 @@
#include <iostream>
#include <nlohmann/json_view.hpp>
using json_document = nlohmann::json_document;
using json_pointer = nlohmann::json::json_pointer;
int main()
{
// "retry_of" is only present on some records, nested a level down
// inside "meta"
json_document batch = json_document::parse(R"(
[
{"id": 1, "meta": {}},
{"id": 2, "meta": {"retry_of": 1}}
]
)");
const auto records = batch.root();
const json_pointer retry_of("/meta/retry_of");
for (std::size_t i = 0; i < records.size(); ++i)
{
const auto record = records[i];
if (record.contains(retry_of))
{
std::cout << "record " << i << " is a retry of " << record[retry_of].get<int>() << '\n';
}
else
{
std::cout << "record " << i << " is original\n";
}
}
// contains() with a JSON pointer never throws -- not even for a
// pointer that indexes into a primitive ("/0/id/x") or uses a
// malformed array index ("/01"), either of which would need a
// try/catch with json::contains(ptr)
std::cout << std::boolalpha << records.contains(json_pointer("/0/id/x")) << '\n';
std::cout << std::boolalpha << records.contains(json_pointer("/01")) << '\n';
}
@@ -0,0 +1,4 @@
record 0 is original
record 1 is a retry of 1
false
false
@@ -0,0 +1,55 @@
#include <iostream>
#include <nlohmann/json_view.hpp>
#include <string>
#include <vector>
using json_document = nlohmann::json_document;
using json_view = nlohmann::json_view;
// address has no direct conversion in get<T>(), so get<address>() falls back
// to materialize().get<address>() -- a real nlohmann::json value is built
// for just this one member, and its own from_json() runs on that
struct address
{
std::string city;
int zip = 0;
};
void from_json(const nlohmann::json& j, address& a)
{
j.at("city").get_to(a.city);
j.at("zip").get_to(a.zip);
}
int main()
{
json_document doc = json_document::parse(R"(
{
"name": "Alice",
"active": true,
"orders": [1, 2, 3],
"address": {"city": "Berlin", "zip": 10115}
}
)");
const json_view customer = doc.root();
// read typed fields straight into C++ variables -- none of these build
// a nlohmann::json value
const std::string name = customer["name"].get<std::string>();
const bool active = customer["active"].get<bool>();
std::cout << name << (active ? " (active)" : " (inactive)") << '\n';
// std::vector<json_view> keeps views of the array elements instead of
// copies of their values
bool first = true;
for (const json_view order : customer["orders"].get<std::vector<json_view>>())
{
std::cout << (first ? "" : " ") << order.get<int>();
first = false;
}
std::cout << '\n';
// everything else goes through materialize()
const address a = customer["address"].get<address>();
std::cout << a.city << ' ' << a.zip << '\n';
}
@@ -0,0 +1,3 @@
Alice (active)
1 2 3
Berlin 10115
@@ -0,0 +1,31 @@
#include <iostream>
#include <nlohmann/json_view.hpp>
#include <string>
using json_document = nlohmann::json_document;
using json_view = nlohmann::json_view;
int main()
{
// a "large response" stand-in: only the "id" field is ever read out of it
const std::string text =
R"({"id": "8f14e45f-ceea-467e-bb92-963f5e3c7a08", "note": "created via API\n", "payload": "..."})";
const json_document doc = json_document::parse(text);
const json_view response = doc.root();
const json_view::string_view_t id = response["id"].get_string();
std::cout << id << '\n';
// no std::string was allocated for "id": its bytes still live inside
// the original buffer, so id's data lies inside [text.data(),
// text.data() + text.size())
const bool id_in_source = id.data() >= text.data() && id.data() + id.size() <= text.data() + text.size();
std::cout << std::boolalpha << id_in_source << '\n';
// "note" contains an escape sequence ('\n'), so it was decoded once
// into the document's own buffer -- get_string() still avoids a copy
// into a new std::string, but the bytes no longer live inside "text"
const json_view::string_view_t note = response["note"].get_string();
const bool note_in_source = note.data() >= text.data() && note.data() + note.size() <= text.data() + text.size();
std::cout << std::boolalpha << note_in_source << '\n';
}
@@ -0,0 +1,3 @@
8f14e45f-ceea-467e-bb92-963f5e3c7a08
true
false
@@ -0,0 +1,28 @@
#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"({"host": "db.example.com", "port": 5432, "ssl": true})");
const json_view config = doc.root();
// get_to() writes directly into existing variables -- handy for filling
// in the members of a struct one field at a time, without an
// intermediate value from get<T>() for each one
std::string host;
int port = 0;
bool ssl = false;
config["host"].get_to(host);
config["port"].get_to(port);
config["ssl"].get_to(ssl);
std::cout << host << ':' << port << (ssl ? " (tls)" : "") << '\n';
// the return value is a reference to the argument, so a call can be
// used directly in a larger expression
std::string other_host;
std::cout << config["host"].get_to(other_host).size() << '\n';
}
@@ -0,0 +1,2 @@
db.example.com:5432 (tls)
14
@@ -0,0 +1,29 @@
#include <iostream>
#include <nlohmann/json_view.hpp>
using json_document = nlohmann::json_document;
using json_view = nlohmann::json_view;
int main()
{
// a price and an order id from an incoming order -- both need to be
// reproduced exactly, e.g. for an invoice or an audit log
json_document doc = json_document::parse(R"(
{"price": 19.90, "order_id": 1234567890123456789012345, "quantity": 3}
)");
const json_view order = doc.root();
// number_token() returns the number exactly as written in the source
std::cout << order["price"].number_token() << '\n';
std::cout << order["order_id"].number_token() << '\n';
// get<double>() converts it instead -- the exact source text is gone:
// "19.90" becomes the double closest to 19.9, printed without the
// trailing zero, and the 25-digit order id -- far beyond any 64-bit
// integer -- can only be approximated as a double
std::cout << order["price"].get<double>() << '\n';
std::cout << order.materialize()["order_id"].dump() << '\n';
// an ordinary quantity has nothing to lose either way
std::cout << order["quantity"].number_token() << " == " << order["quantity"].get<int>() << '\n';
}
@@ -0,0 +1,5 @@
19.90
1234567890123456789012345
19.9
1.2345678901234568e+24
3 == 3
@@ -0,0 +1,47 @@
#include <iostream>
#include <nlohmann/json_view.hpp>
using json_document = nlohmann::json_document;
using json_pointer = nlohmann::json::json_pointer;
int main()
{
// a larger document; operator[] with a JSON pointer reaches straight to
// one deeply nested field, without ever building a tree for the rest
json_document doc = json_document::parse(R"(
{
"region": {
"servers": [
{"name": "eu-1", "metrics": {"cpu": 0.42}},
{"name": "eu-2", "metrics": {"cpu": 0.71}}
]
}
}
)");
const auto root = doc.root();
std::cout << root[json_pointer("/region/servers/1/metrics/cpu")].materialize().dump() << '\n';
// a missing key or an out-of-range index along the path gives a
// discarded view, exactly where const json::operator[] would be
// undefined behavior for the same pointer
if (const auto missing = root[json_pointer("/region/servers/5/metrics/cpu")])
{
std::cout << missing.materialize().dump() << '\n';
}
else
{
std::cout << "no such server\n";
}
// indexing into a primitive still throws, as basic_json::operator[]
// does for the same pointer
try
{
static_cast<void>(root[json_pointer("/region/servers/0/name/x")]);
}
catch (const nlohmann::json::out_of_range& e)
{
std::cout << e.what() << '\n';
}
}
@@ -0,0 +1,3 @@
0.71
no such server
[json.exception.out_of_range.404] unresolved reference token 'x'
@@ -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';
}
}
@@ -0,0 +1,3 @@
localhost
8080
[json.exception.type_error.302] type must be number, but is string
@@ -0,0 +1,21 @@
#include <iostream>
#include <nlohmann/json_view.hpp>
using json_document = nlohmann::json_document;
using json_view = nlohmann::json_view;
using json_pointer = nlohmann::json::json_pointer;
int main()
{
json_document doc = json_document::parse(R"({"server": {"host": "localhost", "limits": {"connections": 100}}})");
const json_view config = doc.root();
// a nested, optional setting read with a default -- no exception, even
// though "timeout" is missing several levels down
std::cout << config.value(json_pointer("/server/limits/connections"), 10) << '\n';
std::cout << config.value(json_pointer("/server/limits/timeout"), 30) << '\n';
// an out-of-range array index also falls back to the default
json_document list_doc = json_document::parse(R"({"servers": ["a", "b"]})");
std::cout << list_doc.root().value(json_pointer("/servers/5"), std::string("none")) << '\n';
}
@@ -0,0 +1,3 @@
100
30
none