【问题标题】:update value of a map of objects更新对象映射的值
【发布时间】:2021-08-28 22:00:27
【问题描述】:

使用 jq,我如何转换以下内容:

{
  "root": {
    "branch1": {
      "leaf": 1
    },
    "branch2": {
      "leaf": 2
    },
    "branch3": {
      "leaf": 3
    }
  },
  "another-root": {
      "branch": 123
  },
  "foo": "bar"
}

到这里:

{
  "root": {
    "branch1": {
      "leaf": "updated"
    },
    "branch2": {
      "leaf": "updated"
    },
    "branch3": {
      "leaf": "updated"
    }
  },
  "another-root": {
      "branch": 123
  },
  "foo": "bar"
}

【问题讨论】:

    标签: json dictionary jq edit


    【解决方案1】:

    ? 显然[] 也可以用于对象。我有,虽然它只是用于列表。

    以下是我所需要的。

    .root[].leaf="updated"

    【讨论】:

    • 在其中一个对象中没有 .leaf 路径的情况下,您仍然需要小心。您的表达式会错误地将其添加到那里,更糟糕的是,如果您有一个包含 .root 内不同元素的数组,那么运行您的表达式将会出错。
    【解决方案2】:

    首先您需要解析 json,然后根据需要使用for ... in 语句修改生成的对象(示例如下)

    const flatJSON = '{"root":{"branch1":{"leaf":1},"branch2":{"leaf":2},"branch3":{"leaf":3}},"another-root":{"branch":123},"foo":"bar"}';
    
    const parsedJSON = JSON.parse(flatJSON);
    const root = parsedJSON.root;
    
    for (let property in root) {
      root[property].leaf = "updated"; (or root[property]["leaf"] = "updated";)
    }
    

    如果您想使用 jquery,您必须将 for ... in 语句替换为 jQuery.each() 方法,该方法会遍历对象和数组。

    不要忘记使用 JSON.stringify() 方法(如果需要)将其转换回 json。

    希望这会有所帮助。 一切顺利。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-19
    • 1970-01-01
    相关资源
    最近更新 更多