Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract json values as array with jq in bash

Tags:

json

bash

jq

How to extract json's values as JSON array with jq?

For example for the below json:

{
   "a" : 1,
   "b" : 2
}

I would like to extract values as JSON array:

[ 1, 2 ]

How to do it with jq? I found a way to extract keys only in the docs:

echo $json | jq keys returns:

[
"a",
"b"
]
like image 786
rok Avatar asked Jun 19 '26 02:06

rok


2 Answers

echo $json | jq '[.[]]'

output:

[
  1,
  2
]
like image 148
gregory Avatar answered Jun 20 '26 23:06

gregory


One solution is to use to_entries then map to extract only the values:

$ echo '{
   "a" : 1,
   "b" : 2
}' | jq 'to_entries|map(.value)'
[
  1,
  2
]

Another solution, simpler and faster, is to use just map(.):

$ echo '{
   "a" : 1,
   "b" : 2
}' | jq 'map(.)'
[
  1,
  2
]
like image 45
axiac Avatar answered Jun 20 '26 21:06

axiac



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!