Skip to content

nlohmann::is_json_view

Defined in header <nlohmann/json_view.hpp>

template<typename T>
struct is_json_view;

A type trait: is_json_view<T>::value is true if T is a basic_json_view of any BasicJsonType and any view_mode -- json_view, json_editable_view, ordered_json_view, ... -- and false otherwise, for basic_json as well.

It is meant for constraining templates that accept views, in particular a from_json() that should read views directly: get<T>() on a view calls a from_json() with the view only if that from_json() accepts views but not arbitrary types.

Template parameters

T
the type to check (without cv-qualifiers or references)

Notes

A view is recognized by its member type basic_json_type (a basic_json specialization) and its materialize() returning that type, so the trait needs no declaration of the view class.

Examples

Example

The example below shows the trait, and a from_json() constrained to json values and views: get<T>() on a view reads the view directly.

#include <iostream>
#include <type_traits>
#include <nlohmann/json_view.hpp>

using nlohmann::json;

namespace ns
{
struct person
{
    std::string name;
    int age = 0;
};

// reads json values and views (of any document type), but nothing else
template < typename J, typename std::enable_if < nlohmann::is_json_view<J>::value || std::is_same<J, json>::value, int >::type = 0 >
void from_json(const J& j, person& p)
{
    p.name = j.at("name").template get<std::string>();
    p.age = j.at("age").template get<int>();
}
} // namespace ns

int main()
{
    std::cout << std::boolalpha
              << nlohmann::is_json_view<nlohmann::json_view>::value << ' '
              << nlohmann::is_json_view<nlohmann::ordered_json_editable_view>::value << ' '
              << nlohmann::is_json_view<json>::value << '\n';

    const nlohmann::json_document doc = nlohmann::json_document::parse(R"({"name": "Ada", "age": 36})");
    const auto p = doc.root().get<ns::person>(); // reads the view, no json value is built
    std::cout << p.name << ' ' << p.age << '\n';
}

Output:

true true false
Ada 36

See also

Version history

Added in version 3.13.0 unreleased.