我正在为现代 C++ 使用 json。 我有一个 json 文件,其中包含一些数据,例如:
{
"London": {
"Adress": "londonas iela 123",
"Name": "London",
"Shortname": "LL"
},
"Riga": {
"Adrese": "lidostas iela 1",
"Name": "Riga",
"Shortname": "RIX"
}
而且我找到了修改“Adrese”、“Name”、“Shortname”值的方法。 如您所见,我将“名称”和关键元素名称设置为相同的内容。
但我需要更改键元素和值“名称”。
所以最后当我以某种方式修改代码时,它看起来像:
{
"Something_New": {
"Adress": "londonas iela 123",
"Name": "Something_New",
"Shortname": "LL"
},
"Riga": {
"Adrese": "lidostas iela 1",
"Name": "Riga",
"Shortname": "RIX"
}
我试过:
/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.
然后我尝试了类似的东西:
for(auto& el : j.items()){
if(el.key() == "London"){
el.key() = "Something_New";}
}
但这也没有用。
我想要像 j["London"] = "Something_new"这样的东西,并让它保留最初用于“伦敦”的所有值。
最佳答案
与键“London”关联的值是包含其他 3 个键及其值的整个子树 json 对象。此行 j["London"] = "Something_New";
不会更改键“London”,但会更改其值。所以你最终得到了一对 "London": "Something new",覆盖了 json 子树对象。 key 在内部存储为 std::map 。因此,您不能简单地重命名这样的键。尝试:
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);
}
然后
change_key(j, "London", "Something_New");
关于c++ - 如何在不更改 C++ 中的值的情况下更改 json 对象名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54387288/