Json: Update/Add object fields

Created on 6 Jul 2017  路  2Comments  路  Source: nlohmann/json

Hi,
Is it possible to modify array address without rewriting existing fields, for example I have this json:
nlohmann::json j = { { "name", "oleg" }, { "address", { "city", "kharkiv" } } };

And I need to add several fields to array address:
j["address"] = nlohmann::json { { "country", "ukraine"}, { "street", "svobody"} };
This variant rewrite array address and I lose data which were in it before I added new one.

So my question is: Is it possible to add data to existing array without loss existing one. Thanks.

question

Most helpful comment

Thanks, it helps:

nlohmann::json jvalue = 
{
    { "name", "oleg" },
    { "address", { { "country", "ukraine" } } }
};

nlohmann::json data
{
    { "street", "svobody" },
    { "city", "kharkiv" }
};
jvalue["address"].insert(data.begin(), data.end());

All 2 comments

I think your example is more about JSON objects than JSON arrays. You can add elements like this:

j["address"]["email"] = "[email protected]";

Alternatively, you can call insert on j["address"].

Thanks, it helps:

nlohmann::json jvalue = 
{
    { "name", "oleg" },
    { "address", { { "country", "ukraine" } } }
};

nlohmann::json data
{
    { "street", "svobody" },
    { "city", "kharkiv" }
};
jvalue["address"].insert(data.begin(), data.end());
Was this page helpful?
0 / 5 - 0 ratings