You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
#include<iostream>
#include"json.hpp"using json = nlohmann::json;
voidchange_key(json &object, const std::string& old_key, const std::string& new_key)
{
// get iterator to old key; TODO: error handling if key is not present
json::iterator it = object.find(old_key);
// create null value for new key and swap value from old keystd::swap(object[new_key], it.value());
// delete value at old key (cheap, because the value is null after swap)
object.erase(it);
}
intmain()
{
json j;
j["foo"] = "value";
std::cout << j << std::endl;
change_key(j, "foo", "bar");
std::cout << j << std::endl;
}
Activity
nlohmann commentedon Dec 27, 2017
This is not possible. JSON objects are stored internally as
std::map. Their keys are const while iterating.gestern commentedon Dec 27, 2017
Thanks, so just to understand, in general, is there any chance to easy rename a key, means without using a pair remove/insert? Like rapidjson:
nlohmann commentedon Dec 28, 2017
You can use this function:
Output:
I just adjusted code from https://stackoverflow.com/a/5743682/266378.