You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何遍历nlohmann JSON所有子节点,将onclick键替换为Click?

替换nlohmann JSON中所有嵌套的"onclick"键为"Click"

我需要处理一个nlohmann JSON对象,要求把所有层级(包括多层嵌套数组里)的"onclick"键全部替换成"Click"。下面是我的示例JSON结构和自己尝试写的代码:

示例JSON

{
  "menu": {
    "id": "file",
    "name": "File",
    "popup": {
      "menuitem": [
        {
          "name": "New",
          "onclick": "CreateDoc()"
        },
        {
          "name": "Open",
          "onclick": "OpenDoc()"
        },
        {
          "name": "Save",
          "onclick": "SaveDoc()"
        },
        {
          "toy": [
            {
              "value": "toyA",
              "onclick": "CreateDoc()"
            },
            {
              "value": "toyB",
              "onclick": "OpenDoc()"
            }
          ]
        }
      ]
    }
  }
}

我尝试的代码

auto change_key = [](nlohmann::json &object, const std::string& old_key, const std::string& new_key) 
{    
    json::iterator it = object.find(old_key);
    while(it != object.end()){
        std::swap(object[new_key], it.value());
        object.erase(it);
        it = object.find(old_key);
    }
};

问题分析

上面的代码只能处理当前层级的JSON对象,没法遍历嵌套的子对象和数组,所以深层嵌套里的"onclick"键不会被替换。

解决方案

需要写一个递归遍历的函数,覆盖JSON里的所有对象和数组:

#include <nlohmann/json.hpp>
using json = nlohmann::json;

void replace_all_keys(json& j, const std::string& old_key, const std::string& new_key) {
    // 处理当前对象的键替换
    if (j.is_object()) {
        auto it = j.find(old_key);
        while (it != j.end()) {
            // 交换值到新键,然后删除旧键
            j[new_key] = std::move(it.value());
            it = j.erase(it);
            // 继续查找当前对象里的旧键(防止多个相同键)
            it = j.find(old_key);
        }

        // 递归遍历所有子值
        for (auto& [key, value] : j.items()) {
            replace_all_keys(value, old_key, new_key);
        }
    } 
    // 处理数组,递归遍历每个元素
    else if (j.is_array()) {
        for (auto& element : j) {
            replace_all_keys(element, old_key, new_key);
        }
    }
    // 其他类型(字符串、数字等)无需处理
}

使用示例

int main() {
    json j = /* 你的示例JSON对象 */;
    replace_all_keys(j, "onclick", "Click");
    
    // 输出替换后的JSON
    std::cout << j.dump(2) << std::endl;
    return 0;
}

运行后,所有层级的"onclick"都会被替换成"Click",包括嵌套数组里的元素。

内容的提问来源于stack exchange,提问作者'H'H'

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 16:24:57