I was currently learning the usage of jq
. I have a json file and I am able to loop through and filter out the values I need from the json. However, I am running into issue when I try to combine the output into single string instead of having the output in multiple lines.
File svcs.json
:
[
{
"name": "svc-A",
"run" : "True"
},
{
"name": "svc-B",
"run" : "False"
},
{
"name": "svc-C",
"run" : "True"
}
]
I was using the jq to filter to output the service names with run
value as True
jq -r '.[] | select(.run=="True") | .name ' svcs.json
I was getting the output as follows:
svc-A
svc-C
I was looking to get the output as single string separated by commas.
Expected Output:
"svc-A,svc-C"
I tried to using join, but was unable to get it to work so far.
CodePudding user response:
The .[]
expression explodes the array into a stream of its elements. You'll need to collect the transformed stream (the names) back into an array. Then you can use the @csv
filter for the final output
$ jq -r '[ .[] | select(.run=="True") | .name ] | @csv' svcs.json
"svc-A","svc-C"
But here's where map
comes in handy to operate on an array's elements:
$ jq -r 'map(select(.run=="True") | .name) | @csv' svcs.json
"svc-A","svc-C"
CodePudding user response:
Keep the array using map
instead of decomposing it with .[]
, then join with a glue string:
jq -r 'map(select(.run=="True") | .name) | join(",")' svcs.json
svc-A,svc-C
If your goal is to create a CSV output, there is a special @csv
command taking care of quoting, escaping etc.
jq -r 'map(select(.run=="True") | .name) | @csv' svcs.json
"svc-A","svc-C"