JQ:将数组组合成单个字符串

JQ: combine arrays into single string

这是我的 json 文件。我想使用 JQ 查询获取字符串 "c,d,e,f,g,h"。

{
    "a1": [
      {
        "group_sourceId": "monday",
        "ids": ["a", "b"]
      },
      {
        "group_sourceId": "sunday",
        "ids": ["c", "d"]
      },
      {
        "group_sourceId": "sunday",
        "ids": ["e", "f"]
      },
      {
        "group_sourceId": "sunday",
        "ids": ["g", "h"]
      }
    ],
    "m1": [
      {
        "group_sourceId": "sunday"
      },
      {
        "group_sourceId": "sunday"
      }
    ]
}

这是我试过的。

cat /tmp/example.json | jq -r '.a1[] | select(.group_sourceId | startswith("星期天")) | .ids'

returns

[
  "c",
  "d"
]
[
  "e",
  "f"
]
[
  "g",
  "h"
]

然后

cat /tmp/example.json | jq -r '.a1[] | select(.group_sourceId | startswith("星期天")) | .ids |加入(“,”)'

c,d
e,f
g,h

考虑到“a1”对象中可能有任意数量的“ids”以及“ids”数组中可能有任意数量的字符串,如何将“c,d,e,f,g,h”作为输出?

[.a1[] | select(.group_sourceId | startswith("sunday")) | .ids[]] | sort[]

生成排序列表。如果您想要唯一值,请使用 unique 而不是 sort。如果您希望输出为一行 CSV,您可以将最后的 [] 替换为 | @csv

另一种使用 map 的方法。此外,您可以使用 == 来测试完全匹配。

jq -r '.a1 | map(select(.group_sourceId == "sunday").ids[]) | join(",")'
c,d,e,f,g,h

Demo