Reinis Zīverts
Reinis Zīverts

Reputation: 43

How to change json object name without changing its values in C++?

I'm using json for modern c++. And I have a json file which contains some data like:

 {
"London": {
    "Adress": "londonas iela 123",
    "Name": "London",
    "Shortname": "LL"
},
"Riga": {
    "Adrese": "lidostas iela 1",
    "Name": "Riga",
    "Shortname": "RIX"
}

And I found out a way to modify the values of "Adrese", "Name", "Shortname". As you can see I have "name" and key element name set to the same thing.

But I need to change both the key element and value "name".

So at the end when somehow in the code I modify it, it would look like:

{
"Something_New": {
    "Adress": "londonas iela 123",
    "Name": "Something_New",
    "Shortname": "LL"
},
"Riga": {
    "Adrese": "lidostas iela 1",
    "Name": "Riga",
    "Shortname": "RIX"
}

I've tried:

 /other_code/
 json j
 /functions_for_opening_json file/ 
 j["London"]["Name"] = "Something_New"; //this changes the value "name"
 j["London"] = "Something_New"; //But this replaces "London" with 
 "Something_new" and deletes all of its inside values.

Then I tried something like:

for(auto& el : j.items()){
if(el.key() == "London"){
el.key() = "Something_New";}
}

But that didn't work either.

I would like something like j["London"] = "Something_new", and for it to keep all the values that originally was for "London".

Upvotes: 1

Views: 2330

Answers (1)

Attersson
Attersson

Reputation: 4866

The value associated with key "London" is the entire subtree json object containing the other 3 keys with their values. This line j["London"] = "Something_New"; does not change the key, "London" but its value. So you end up with the pair "London" : "Something new", overwriting the json subtree object. The keys are stored internally as std::map . Therefore you can't simply rename a key like that. Try:

void change_key(json &j, const std::string& oldKey, const std::string& newKey)
{
    auto itr = j.find(oldKey); // try catch this, handle case when key is not found
    std::swap(j[newKey], itr.value());
    object.erase(itr);
}

And then

change_key(j, "London", "Something_New");

Upvotes: 1

Related Questions