2

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"
]
3
  • 1
    The keys a, b, need to be double quoted for jq to parse it as a valid JSON Commented Dec 26, 2019 at 16:46
  • 1
    Do you mean as a JSON array, or as a Bash array, or just the values, one per line? Commented Dec 26, 2019 at 16:46
  • @tripleee json array, similar to keys filter Commented Dec 26, 2019 at 16:49

2 Answers 2

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

output:

[
  1,
  2
]
Sign up to request clarification or add additional context in comments.

Comments

3

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
]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.