JSON for Modern C++ 3.10.4

◆ emplace()

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, class BinaryType = std::vector<std::uint8_t>>
template<class... Args>
std::pair< iterator, bool > nlohmann::basic_json< ObjectType, ArrayType, StringType, BooleanType, NumberIntegerType, NumberUnsignedType, NumberFloatType, AllocatorType, JSONSerializer, BinaryType >::emplace ( Args &&...  args)

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.

[in]argsarguments to forward to a constructor of basic_json
Template Parameters
Argscompatible types to create a basic_json object
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.
type_error.311when called on a type other than JSON object or null; example: "cannot use emplace() with number"
Logarithmic in the size of the container, O(log(size())).
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 <iostream>
2#include <nlohmann/json.hpp>
4using json = nlohmann::json;
6int main()
8 // create JSON values
9 json object = {{"one", 1}, {"two", 2}};
10 json null;
12 // print values
13 std::cout << object << '\n';
14 std::cout << null << '\n';
16 // add values
17 auto res1 = object.emplace("three", 3);
18 null.emplace("A", "a");
19 null.emplace("B", "b");
21 // the following call will not add an object, because there is already
22 // a value stored at key "B"
23 auto res2 = null.emplace("B", "c");
25 // print values
26 std::cout << object << '\n';
27 std::cout << *res1.first << " " << std::boolalpha << res1.second << '\n';
29 std::cout << null << '\n';
30 std::cout << *res2.first << " " << std::boolalpha << res2.second << '\n';
basic_json<> json
default JSON class
Definition: json.hpp:3472

Output (play with this example online):
3 true
"b" false
The example code above can be translated with
g++ -std=c++11 -Isingle_include doc/examples/emplace.cpp -o emplace 
version 2.0.8

Definition at line 23205 of file json.hpp.