首页 > 解决方案 > 如何在不更改 C++ 中的值的情况下更改 json 对象名称?

问题描述

我正在将 json 用于现代 C++。我有一个 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" 的所有值。

标签: c++nlohmann-json

解决方案


与键“London”关联的值是包含其他 3 个键及其值的整个子树 json 对象。此行j["London"] = "Something_New";不会更改键“London”,而是更改其值。所以你最终得到一对“伦敦”:“新事物”,覆盖了 json 子树对象。密钥在内部存储为 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");

推荐阅读