Home > Back-end >  Select key:value with jq and output as array
Select key:value with jq and output as array

Time:07-11

When using jq it is easy to select a key:value that you want to output, but by default the array dissapears. How do I keep the output as an array?

Example

# My JSON
my_json='{"count":2,"values":[{"name": "Hans","age": 22},{"name": "John","age": 88}]}'

# Getting names
echo $my_json | jq ".values[].name"
"Hans"
"John"

What I want

["Hans", "John"]

With an output like that I can e.g. remove the quotes by outputting it to tsv.

# Output to tsv
echo '["Hans", "John"]' | jq -r '.[]'

CodePudding user response:

You can add square brackets along with c(ompact output) option such as

echo $my_json | jq -c '[.values[].name]'

Demo

  • Related