c++ - 如何在不更改 C++ 中的值的情况下更改 json 对象名称?

标签 c++ nlohmann-json

我正在为现代 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/

相关文章:

c++ - 从 ASSERT_THROW 获取异常信息

c++ - 如何在 Visual Studio 中使用预编译库构建应用程序

c++ - 使用同步或异步的单线程连接多个客户端?

c++ - 如何使用 vn_rdwr() API 组合 osx 内核扩展中的两个文件

python - 带有 GDB : the case of nlohmann json library 的 C++ 调试/打印自定义类型

c++ - 将 json 文件转换为 json 对象会打乱对象的顺序

c++ - 闭源库包括 boost 分发

c++ nlohmann json - 如何测试嵌套对象是否存在或为空

C++ nlohmann JSON 获取数组名称