shell jq -使用数组取消嵌套/展开对象,即为嵌套数组中的每一项创建新对象

x4shl7ld  于 2022-12-13  发布在  Shell
关注(0)|答案(2)|浏览(172)

我不确定这里的操作名称是否正确,但这个例子应该很好地表明了我的意图。这正是Mongo中的展开聚合操作或BigQuery中的unnest的行为方式。
具有json结构的:

[
  {
    "root-array-a": [
      11,
      12,
      13
    ],
    "root-property-b": 22,
    "root-property-c": 33
  }
]

我想得到一个结果:

[
  {
    "root-property-a": 11,
    "root-property-b": 22,
    "root-property-c": 33
  },
  {
    "root-property-a": 12,
    "root-property-b": 22,
    "root-property-c": 33
  },
  {
    "root-property-a": 13,
    "root-property-b": 22,
    "root-property-c": 33
  },
]
piah890a

piah890a1#

这是可行的:

jq 'map({"root-property-a": ."root-array-a"[]} + . | del(."root-array-a"))'

{"root-property-a": ."root-array-a"[]}root-array-a中的每个值构造一个带有root-property-a键的对象(因为[]运算符,并且因为jq根据需要隐式扇出多个输出)。+ .将该键添加到原始对象,并且del删除不需要的数组。

yzckvree

yzckvree2#

在构造一个对象时,可以使用stream数组,该对象将生成每种输入组合:

map({
    "root-property-a": ."root-array-a"[],
    "root-property-b": ."root-property-b",
    "root-property-c": ."root-property-c"
})

输出量:

[
  {
    "root-property-a": 11,
    "root-property-b": 22,
    "root-property-c": 33
  },
  {
    "root-property-a": 12,
    "root-property-b": 22,
    "root-property-c": 33
  },
  {
    "root-property-a": 13,
    "root-property-b": 22,
    "root-property-c": 33
  }
]

相关问题