Reputation: 3335
Anyone has idea how to quickly copy nlohmann::json
MAP values to an other nlohmann::json
?
nlohmann::json j1;
nlohmann::json j2;
j1["MAP"]["value1"] = 1;
j2["MAP"]["value2"] = 2;
j2["MAP"] += j1["MAP"];
This will throw because +=
will think that I am adding a value to a list.
[json.exception.type_error.308] cannot use push_back() with object
I can enumerate j1["MAP"]
and add them into j2["MAP"]
but I was wondering if there is a straightforward method.
Upvotes: 2
Views: 2474
Reputation: 48278
Another alternative to @cdhowie 's answer is to merge those objects, here the method that you need: merge_patch
so your code should look like:
nlohmann::json j1;
nlohmann::json j2;
j1["MAP"]["value1"] = 1;
j2["MAP"]["value2"] = 2;
//j2["MAP"] += j1["MAP"];
j2.merge_patch(j1);
std::cout << "j2: " << j2.dump().c_str() << std::endl;
and will produce a result like this:
j2: {"MAP":{"value1":1,"value2":2}}
NOTE: even though the result is the same using update or merge_patch there are some differences in the behavior of those methods: I quote the sir nlohmann, who developed the lib
so in the end is up to you to choose the method that better fits your applications requirements
Upvotes: 1
Reputation: 169028
The json::update()
method is the built-in version of this operation.
j2["MAP"].update(j1["MAP"]);
Upvotes: 4