JSON for Modern C++  2.1.1
template<template< typename U, typename V, typename...Args > class ObjectType = std::map, template< typename U, typename...Args > class ArrayType = std::vector, class StringType = std::string, class BooleanType = bool, class NumberIntegerType = std::int64_t, class NumberUnsignedType = std::uint64_t, class NumberFloatType = double, template< typename U > class AllocatorType = std::allocator, template< typename T, typename SFINAE=void > class JSONSerializer = adl_serializer>
template<class... Args>
std::pair<iterator, bool> nlohmann::basic_json::emplace ( Args &&...  args)
inline

Inserts a new element into a JSON object constructed in-place with the given args if there is no element with the key in the container. If the function is called on a JSON null value, an empty object is created before appending the value created from args.

Parameters
[in]argsarguments to forward to a constructor of basic_json
Template Parameters
Argscompatible types to create a basic_json object
Returns
a pair consisting of an iterator to the inserted element, or the already-existing element if no insertion happened, and a bool denoting whether the insertion took place.
Exceptions
std::domain_errorwhen called on a type other than JSON object or null; example: "cannot use emplace() with number"
Complexity
Logarithmic in the size of the container, O(log(size())).
Example
The example shows how emplace() can be used to add elements to a JSON object. Note how the null value was silently converted to a JSON object. Further note how no value is added if there was already one value stored with the same key.
1 #include <json.hpp>
2 
3 using json = nlohmann::json;
4 
5 int main()
6 {
7  // create JSON values
8  json object = {{"one", 1}, {"two", 2}};
9  json null;
10 
11  // print values
12  std::cout << object << '\n';
13  std::cout << null << '\n';
14 
15  // add values
16  auto res1 = object.emplace("three", 3);
17  null.emplace("A", "a");
18  null.emplace("B", "b");
19 
20  // the following call will not add an object, because there is already
21  // a value stored at key "B"
22  auto res2 = null.emplace("B", "c");
23 
24  // print values
25  std::cout << object << '\n';
26  std::cout << *res1.first << " " << std::boolalpha << res1.second << '\n';
27 
28  std::cout << null << '\n';
29  std::cout << *res2.first << " " << std::boolalpha << res2.second << '\n';
30 }
basic_json<> json
default JSON class
Definition: json.hpp:12369
Output (play with this example online):
{"one":1,"two":2}
null
{"one":1,"three":3,"two":2}
3 true
{"A":"a","B":"b"}
"b" false
The example code above can be translated with
g++ -std=c++11 -Isrc doc/examples/emplace.cpp -o emplace 
Since
version 2.0.8

Definition at line 5492 of file json.hpp.