jq Filter:提取父值+数组的唯一值

时间:2016-06-28 16:32:23

标签: json jq

这是一个JSON示例:

[
  {
    "AAA": "111",
    "images": [
      {
        "BBB": "some_value1"
      },
      {
        "BBB": "some_value2"
      },
      {
        "BBB": "some_value3"
      }
    ]
  },
  {
    "AAA": "222",
    "images": [
      {
        "BBB": "some_value4"
      },
      {
        "BBB": "some_value5"
      },
      {
        "BBB": "some_value6"
      }
    ]
  }
]

以下过滤器几乎解决了所需的任务:

cat EXAMPLE.json | jq -r ".[] | [.AAA, .images[].BBB] | @csv"

但是,它只给出了这样的结果:

"111","some_value1","some_value2","some_value3"
"222","some_value4","some_value5","some_value6"

问题是:如何更改我的jq过滤器以获得以下结果:

"111","some_value1"
"111","some_value2"
"111","some_value3"
"222","some_value4"
"222","some_value5"
"222","some_value6"

感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

你可以这样做:

$ jq -r '.[] | [.AAA] + (.images[] | [.BBB]) | @csv' EXAMPLE.json

答案 1 :(得分:0)

略微修改fkrents初始尝试:

.[] | [.AAA, .images[].BBB] | @csv

导致这个解决方案:

.[] | .AAA as $a | .images[].BBB | [$a, .] | @csv