Skip to content

nlohmann::basic_json::object

staticbasic_jsonobject(initializer_list_tinit={});

Creates a JSON object value from a given initializer list. The initializer lists elements must be pairs, and their first elements must be strings. If the initializer list is empty, the empty object {} is created.

Parameters

init (in)
initializer list with JSON values to create an object from (optional)

Return value

JSON object value

Exception safety

Strong guarantee: if an exception is thrown, there are no changes in the JSON value.

Exceptions

Throws type_error.301 if init is not a list of pairs whose first elements are strings. In this case, no object can be created. When such a value is passed to basic_json(initializer_list_t, bool, value_t), an array would have been created from the passed initializer list init. See the example below.

Complexity

Linear in the size of init.

Notes

This function is only added for symmetry reasons. In contrast to the related function array(initializer_list_t), there are no cases that can only be expressed by this function. That is, any initializer list init can also be passed to the initializer list constructor basic_json(initializer_list_t, bool, value_t).

Examples

Example

The following code shows an example for the object function.

#include<iostream>
#include<nlohmann/json.hpp>
usingjson=nlohmann::json;
intmain()
{
// create JSON objects
jsonj_no_init_list=json::object();
jsonj_empty_init_list=json::object({});
jsonj_list_of_pairs=json::object({{"one",1},{"two",2}});
// serialize the JSON objects
std::cout<<j_no_init_list<<'\n';
std::cout<<j_empty_init_list<<'\n';
std::cout<<j_list_of_pairs<<'\n';
// example for an exception
try
{
// can only create an object from a list of pairs
jsonj_invalid_object=json::object({{"one",1,2}});
}
catch(constjson::type_error&e)
{
std::cout<<e.what()<<'\n';
}
}

Output:

{}
{}
{"one":1,"two":2}
[json.exception.type_error.301]cannotcreateobjectfrominitializerlist

See also

Version history

  • Added in version 1.0.0.

AltStyle によって変換されたページ (->オリジナル) /