Here is my json file. I would like to get string "c,d,e,f,g,h" using JQ query.
{
"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"
}
]
}
This is what I tried.
cat /tmp/example.json | jq -r '.a1[] | select(.group_sourceId | startswith("sunday")) | .ids'
returns
[
"c",
"d"
]
[
"e",
"f"
]
[
"g",
"h"
]
then
cat /tmp/example.json | jq -r '.a1[] | select(.group_sourceId | startswith("sunday")) | .ids | join(",")'
c,d
e,f
g,h
How to get "c,d,e,f,g,h" as a output considering there could be any number of "ids" in "a1" object and any number of strings in "ids" array?
CodePudding user response:
Another approach using map
. Also, you could use ==
to test for an exact match.
jq -r '.a1 | map(select(.group_sourceId == "sunday").ids[]) | join(",")'
c,d,e,f,g,h
CodePudding user response:
[.a1[] | select(.group_sourceId | startswith("sunday")) | .ids[]] | sort[]
produces the sorted listing. If you want the unique values, use unique
instead of sort
. If you want the output as a line of CSV, you could replace the final []
with | @csv
.