nlohmann::basic_json_view::get¶
template<typename T>
T get() const;
Converts the value to T.
For the types below, the conversion works directly on the flat index — no BasicJsonType value is built for it:
bool- arithmetic types other than
bool(for a boolean,0/1, exactly as forBasicJsonType::get<T>()) std::nullptr_tstd::basic_string<char, Traits, Alloc>(includingstring_t) — a copy of the stringstring_view_t— no copy: the returned view points into the document'ssource()text, or, for a string that contains escape sequences, into the document's own buffer of decoded strings (seeget_string())BasicJsonType— equivalent tomaterialize()basic_json_view— returns*thisstd::vector<U, A>of the types above — from an array, element by element, each converted withget<U>();std::vector<basic_json_view>keeps a view of every element instead of a valuestd::map<K, basic_json_view, C, A>andstd::unordered_map<K, basic_json_view, H, E, A>, ifKis constructible from a(const char*, std::size_t)pair — views of the members of an object; with a repeated key, the view of the last member is kept, asBasicJsonType::parse()keeps its value
A default-constructible T whose from_json() accepts views reads the view directly as well, without building a BasicJsonType value. This covers the library's own conversions of the standard library types — all other std::vectors, std::map/std::unordered_map (also with other key types), std::list, std::deque, std::set, std::forward_list, std::valarray, std::array, C arrays, std::pair, std::tuple, std::optional, enumerations, std::filesystem::path, ... -- which give the same values as materialize().get<T>() (from an object, a repeated key keeps the last value, as BasicJsonType::parse() does), as well as the types of the NLOHMANN_DEFINE_TYPE_* and NLOHMANN_DEFINE_DERIVED_TYPE_* macros and the enumerations of NLOHMANN_JSON_SERIALIZE_ENUM, and any from_json() constrained to accept views, e.g. with is_json_view. A from_json() that also accepts types that are no JSON values at all, such as the unconstrained template<typename BasicJsonType> void from_json(const BasicJsonType&,T&) of arbitrary type conversions, is not called with a view: it may use BasicJsonType functions a view does not have. See Writing generic code.
Duplicate keys
Such a from_json() looks members up in the view, where a repeated key finds the first member, while materialize().get<T>() sees the last one, as BasicJsonType::parse() keeps it: for {"x":1,"x":2}, get<point>() reads x == 1. See Duplicate keys.
Every other T — user types whose from_json() is written for BasicJsonType only, types without a default constructor, std::tuples holding references, ... — is converted by materialize().get<T>(): the subtree is built into a real BasicJsonType value first (as BasicJsonType::parse() would), and converted from there exactly as BasicJsonType::get<T>() would convert it.
Template parameters¶
T- the type to convert the value to
Return value¶
the value, converted to T
Exception safety¶
Strong guarantee: there are no changes to the view or the document it refers to.
Exceptions¶
- For the directly-converted types listed above (other than
BasicJsonTypeandbasic_json_view, which never throw): throwstype_error.302if the value's type does not matchT— the same exception, with the same message, thatBasicJsonType::get<T>()throws for the same JSON type andT. - For
std::vector<U, A>: throwstype_error.302if the value is not an array; otherwise, whatever converting an element toUthrows. - For
std::map/std::unordered_mapof views: throwstype_error.302if the value is not an object. - For a
Twhosefrom_json()reads the view: whatever thatfrom_json()throws; for the library's conversions and the macros, the same exceptions with the same messages asBasicJsonType::get<T>()of the same value. - For every other
T: whatevermaterialize().get<T>()throws — typicallytype_error.302, or whatever a user-providedfrom_json()throws.
The exceptions thrown directly by this function or by a from_json() that reads the view (the first four bullets above) carry the context of those of BasicJsonType: with JSON_DIAGNOSTICS the JSON Pointer path of the value within the document, and with JSON_DIAGNOSTIC_POSITIONS its bytes in the source text. An exception thrown while converting through materialize() (the last bullet) is thrown by the materialized BasicJsonType value instead: its path is relative to the root of the view's subtree, because materialize() builds only the subtree (with parent pointers), so it is empty if the failing value is the subtree's root itself.
Complexity¶
bool, arithmetic types,std::nullptr_t,string_view_t,basic_json_view: constant.std::basic_string<char, Traits, Alloc>: constant, plus one allocation and a copy of the string's bytes.BasicJsonType: linear in the size of the subtree, seematerialize().std::vector<U, A>: linear in the number of elements, times the complexity of converting one element toU.std::map/std::unordered_map: linear in the number of members for walking them, plus the container's own insertion cost per member (logarithmic forstd::map, amortized constant forstd::unordered_map), times the complexity of converting one member to the mapped type.- a
Twhosefrom_json()reads the view: the cost of thatfrom_json(); for the macros, linear in the number of members times the cost of a lookup, plus the cost of converting the members. - every other
T: the cost ofmaterialize()and of destroying theBasicJsonTypevalue afterwards, plus that ofBasicJsonType::get<T>().
Notes¶
Floating-point values
A floating-point T is converted from the same digits the lexer would see during BasicJsonType::parse(), using the same conversion, so the result is bit-for-bit identical to BasicJsonType::parse(text).get<T>() for the same source text.
Duplicate keys
std::map/std::unordered_map conversions keep the last value of a repeated key, like materialize() and BasicJsonType::parse() do. This is the opposite of operator[]/at/find/contains, which resolve to the first occurrence (see the Notes on duplicate keys).
No pointers, references, or implicit conversion
Unlike BasicJsonType, basic_json_view has no stored value anywhere to hand out a pointer or a reference to, so it provides neither get_ptr(), get_ref(), nor operator ValueType(). get_string() (equivalently, get<string_view_t>()) is the zero-copy alternative for strings.
Examples¶
Example
The example below reads typed fields straight into C++ variables, collects a view of every array element with get<std::vector<basic_json_view>>() instead of a value, and converts a nested object into a user type through its from_json() — which runs on a BasicJsonType value materialize() builds for just that one member.
#include <iostream>
#include <nlohmann/json_view.hpp>
#include <string>
#include <vector>
using nlohmann::json_document;
using 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';
}
Output:
Alice (active)
1 2 3
Berlin 10115
See also¶
get_to- convert and write into a passed valueget_string- the string, without a copynumber_token- a number's token text, without a copymaterialize- build theBasicJsonTypevalue of this subtreeBasicJsonType::get- the corresponding function ofbasic_json- Zero-copy JSON views - which conversions avoid building a basic_json value
Version history¶
- Added in version 3.13.0 unreleased.