使用JQ根据条件在特定位置注入元素

Using JQ to inject element at specific position based on conditions

扯到这里,尝试用jq解析和扩展一个JSON文件,并根据一定条件在特定位置添加元素。 这是一个示例文件(也在 https://jqplay.org/s/6cjmbnvrqu

{
  "TopA": { "stuff": "here"},
  "TopB": {
    "C591AB7E": {
      "Type": "this",
      "Properties": {
        "lots": 1,
        "of": 2,
        "values" : 3
      }
    },
    "7E16765A": {
      "Type": "this",
      "Properties": {
        "lots": 4,
        "of": 5,
        "values" : 6
      }
    },
    "AAD76465": {
      "Type": "that",
      "Properties": {
        "lots": 7,
        "of": 8,
        "values" : 9
      }
    }
  }
}

目标是将元素添加到任何 TopB child 的 Properties 节点,其中 .Type == "that"。更重要的是,我需要将 child 节点的键放入带有添加前缀的新元素值中。 所以基本上我需要最后一个元素看起来像这样:

"AAD76465": {
  "Type": "that",
  "Properties": {
    "lots": 7,
    "of": 8,
    "values": 9,
    "newElement": "Prefix-AAD76465"
  }
}

我还需要保留整个文件的其余部分(或与此相关的新文件)。所以我不需要查询,而是真正需要 jq 调用来操作现有文件。与 TopB 并行,文件中可能还有其他我仍然需要的元素。不,我不知道,我也无法控制 TopB 的 children 的命名。我所拥有的只是我的目标嵌套在 TopB 的 children 中,带有 .Type == "that"。可以有多个。

感谢观看。

如果您获得了首先添加新字段的路径,您可以简单地从中提取父键。

reduce path(.TopB[] | select(.Type == "that") .Properties.newElement) as $p (.; setpath($p; "Prefix-\($p[1])"))

Online demo

这是一个使用 walk/1 的解决方案,因此可能非常直观:

walk(if (type == "object") and .TopB
     then .TopB |= with_entries( 
       .key as $key
       | if .value.Type == "that" 
         then .value.Properties += { newElement: ("Prefix-" + $key) }
         else . end)
     else . end)

此解决方案的一个优点是它满足规定的要求:

The goal is to add an element to the Properties node of any TopB child ...

从某种意义上说,没有对带有“topB”键的对象的位置做出任何假设。