I have a JSON output that contains a list of objects stored in a variable. (I may not be phrasing that right)
[
{
"item1": "value1",
"item2": "value2",
"sub items": [
{
"subitem": "subvalue"
}
]
},
{
"item1": "value1_2",
"item2": "value2_2",
"sub items_2": [
{
"subitem_2": "subvalue_2"
}
]
}
]
I need all the values for item2 in a array for a bash script to be run on ubuntu 14.04.1.
I have found a bunch of ways to get the entire result into an array but not just the items I need
Using jq :
$ cat json
[
{
"item1": "value1",
"item2": "value2",
"sub items": [
{
"subitem": "subvalue"
}
]
},
{
"item1": "value1_2",
"item2": "value2_2",
"sub items_2": [
{
"subitem_2": "subvalue_2"
}
]
}
]
arr=( $(jq -r '.[].item2' json) )
printf '%s\n' "${arr[@]}"
value2
value2_2
jq . <<< "$json"
it's shell (bash) related, non specific to jq
— Jan 07, 2015 at 00:23 arr=( $(...) )
— Jan 07, 2015 at 00:35 jq
command, but please don't parse command output into an array with arr=( $(...) )
(even though it happens to work with the sample input): it doesn't work as intended with embedded or leading/trailing whitespace and can result in accidental globbing. — Jul 14, 2016 at 05:21