nlohmann::basic_json::get - renxiaobo27/json GitHub Wiki

template<typename T>
T get() const;

Description

Returns the value of a JSON container in a variety of types.

Parameters

None.

Return value

The return value is the JSON container's value casted to the return value type T. The following type lists compatible types for the different JSON value types.

value type compatible types
null none
boolean boolean_t, bool
string any type convertible from string_t
number any arithmetic type (that is, an integral type or a floating-point type)
object object_t, any associative container whose key_type convertible from string_t and whose mapped_type is convertible from basic_json
array array_t, any sequence container whose value_type is convertible from basic_json; furthermore, std::set and std::unordered_set with the same constraints are allowed

Note that in case of objects and arrays, all values must be compatible.

Complexity

Amortized linear in the size of the JSON type.

Exceptions

std::std::logic_error if types are not compatible.

Example

#include <json.hpp>
#include <vector>
#include <list>
#include <unordered_set>
#include <map>
#include <string>

int main()
{
    nlohmann::json j1 = {1, 2, 3.2, 4.3, 5.4};
    auto v11 = j1.get<std::vector<float>>();
    auto v12 = j1.get<std::list<int>>();
    auto v13 = j1.get<std::unordered_set<float>>();

    nlohmann::json j2 = {{"one", 1}, {"two", 2}, {"three", 3}};
    auto v21 = j2.get<std::map<std::string, size_t>>();
    auto v22 = j2.get<std::multimap<std::string, double>>();

    nlohmann::json j3 = "Hello, world";
    auto v31 = j3.get<std::string>();
}

See also

⚠️ **GitHub.com Fallback** ⚠️