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

已知键时如何更新嵌套JSON中的值?

根据点分隔键路径更新嵌套JSON值

核心思路是将点分隔的键路径拆分为单个键的数组,然后逐层遍历嵌套对象,定位到目标属性后完成赋值。以下是两种常用编程语言的实现示例:

JavaScript 实现

// 原始嵌套JSON对象
const nestedObj = {
  "fontweight": {
    "primary": {
      "weight1": {
        "value": "Regular",
        "type": "fontWeights"
      },
      "weight2": {
        "value": "SemiBold",
        "type": "fontWeights"
      }
    }
  }
};

// 待更新的键值对
const updatePair = {
  key: "fontweight.primary.weight1.value",
  value: "Bold"
};

// 更新函数
function updateNestedObject(obj, keyPath, newValue) {
  const keys = keyPath.split('.');
  // 遍历到倒数第二个键,获取目标父对象
  const targetParent = keys.slice(0, -1).reduce((current, key) => {
    // 若中间键不存在,自动创建空对象(可根据需求改为抛出错误)
    if (!current[key]) current[key] = {};
    return current[key];
  }, obj);
  // 给最后一个键赋值
  targetParent[keys.pop()] = newValue;
}

// 执行更新
updateNestedObject(nestedObj, updatePair.key, updatePair.value);
console.log(nestedObj.fontweight.primary.weight1.value); // 输出 "Bold"

Python 实现

# 原始嵌套JSON对象
nested_obj = {
  "fontweight": {
    "primary": {
      "weight1": {
        "value": "Regular",
        "type": "fontWeights"
      },
      "weight2": {
        "value": "SemiBold",
        "type": "fontWeights"
      }
    }
  }
}

# 待更新的键值对
update_pair = {
  "key": "fontweight.primary.weight1.value",
  "value": "Bold"
}

# 更新函数
def update_nested_object(obj, key_path, new_value):
    keys = key_path.split('.')
    target_parent = obj
    # 遍历到倒数第二个键
    for key in keys[:-1]:
        # 若中间键不存在,自动创建空字典(可根据需求改为抛出错误)
        if key not in target_parent:
            target_parent[key] = {}
        target_parent = target_parent[key]
    # 给最后一个键赋值
    target_parent[keys[-1]] = new_value

# 执行更新
update_nested_object(nested_obj, update_pair["key"], update_pair["value"])
print(nested_obj["fontweight"]["primary"]["weight1"]["value"]) # 输出 "Bold"

注意事项

  • 上述代码默认会自动创建不存在的中间键对应的空对象/字典,若需要严格校验键路径的合法性,可将创建逻辑替换为抛出异常(比如throw new Error('键路径不存在')或raise KeyError('键路径不存在'))。
  • 如果键路径包含数组索引(如a.b[0].c),需要额外解析索引部分,将其转换为数字后访问数组元素。

内容的提问来源于stack exchange,提问作者U. Watt

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 06:22:49