Files
json/docs/mkdocs/docs/examples/json_view_ownership.cpp
T
Niels Lohmann 061c30310e Document json_document and json_view
- API pages for basic_json_document and basic_json_view, one per member,
  and for the four aliases, each with an example
- features/json_view.md: the problem the view solves, ownership and
  lifetime, what matches basic_json::parse() and what differs, and when
  to choose json, ordered_json, SAX, or the view
- the examples show why one would use the view, not only how: borrowed
  vs. owned input, reading a few fields and materializing one subtree,
  reusing a document across many messages
- registered in the mkdocs navigation, llms.txt, the docset, the
  exceptions page (out_of_range.416), architecture.md, the integration
  page, and the README; the yyjson credit is added to the README and
  license.md

Signed-off-by: Niels Lohmann <mail@nlohmann.me>
2026-09-30 20:58:44 +02:00

34 lines
1.1 KiB
C++

#include <iostream>
#include <string>
#include <utility>
#include <nlohmann/json_view.hpp>
using json_document = nlohmann::json_document;
int main()
{
std::cout << std::boolalpha;
// BORROWED: doc only points into `text`; `text` must outlive `doc`
std::string text = R"({"a": 1})";
json_document doc = json_document::parse(text);
std::cout << doc.owns_source() << '\n'; // false
// a view is valid as long as the document is alive, has not been
// re-parsed (read()) or shrunk (shrink_to_fit()), and -- if borrowed --
// the source text is alive
nlohmann::json_view v = doc.root();
std::cout << v.is_object() << '\n';
// re-parsing the SAME document invalidates views taken before the call;
// `v` above must not be used after this line
doc.read(R"([1, 2, 3])");
v = doc.root(); // take a fresh view instead
std::cout << v.is_array() << '\n';
// moving the document does not invalidate views: the node index is
// heap-allocated and does not move with the document object
json_document moved = std::move(doc);
std::cout << v.is_array() << '\n';
}