Select key:value with jq and output as array

Viewed 59

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 '.[]'
2 Answers

You can add square brackets (preferably along with c(ompact output) option in order to return the array on a single line as in the question) such as

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

Demo

No need for two commands. You can directly get

Hans
John

by using

printf %s "$my_json" | jq -r '.values[].name'

Demo on jqplay

Related