如何为jq中的每个内部数组元素打印对象元素

How to print object element for each internal array element in jq

我有 JSON 看起来像这样:

test.json

[
  {
    "item1": {
      "item2": 123,
      "array1": [
        {
          "item3": 456,
          "item4": "teststring"
        },
        {
          "item3": 789,
          "item4": "teststring2"
        }
      ]
    }
  }
]

我正在尝试按以下格式打印出来:

123, 456, teststring
123, 789, teststring2

我试过这样做:

cat test.json | jq -r '.[].item1.item2, (.[].item1.array1[] | .item3, .item4)' | xargs printf "%s, %s, %s\n"

但是结果是打印了item2,后面第一行是item3item4,然后只有item3item4在下一行打印,如下所示:

123, 456, teststring
789, teststring2, 

如何为从数组内部打印的每组元素打印数组外部的元素?

这会有所帮助

https://jqplay.org/s/KLPXwB7Ey_

.[].item1 as $item | $item.array1[] | $item.item2 , .item3 , .item4

不需要使用 shell 的 printf()xargs 进行输出处理,因为您可以完全在 jq 本身中进行处理。

您需要每次迭代 .item3.item4 的值以获得一个唯一值 .item2。要获得正确的 CSV 格式的结果,请使用 @csv 格式化数组,对于表格表示,您可以使用 @tsv

jq -r '.[].item1 as $data | $data.array1[] | [ $data.item2 , .item3 , .item4 ] | @csv' json

此外,在预期输出中丢失 .item4 值周围的引号也没有意义,因为它们预计会保留在有效的 JSON 字符串属性中。

如果您仍然需要松开引号并将它们表示为原始字符串,您可以在形成的数组上使用 join

jq -r '.[].item1 as $data | $data.array1[] | [ ($data.item2|tostring) , (.item3|tostring) , .item4 ]|join(", ")'