Reputation: 18629
i have a json file
{
"file" : {
"a" : 1,
"b" : 2
}
}
I am using jq
to count number of keys file value have in this json object.
then using on bash
arr=($(cat jsonfile.json | jq '.file' | jq -r 'keys'))
echo ${#arr[@]}
here i get output 4 whereas there is only 2 keys a,b
Why is that so, and how do i get arr only have two elements a
and b
.?
Upvotes: 1
Views: 1094
Reputation: 124764
To understand why you get an array of 4 elements, look at the output of the sub-shell:
cat jsonfile.json | jq '.file' | jq -r 'keys'
This produces:
[ "a", "b" ]
Each line there becomes an element of the array -> 4 lines.
Try this instead:
jq -r '.file | keys | .[]' jsonfile.json
Output:
a b
I also simplified your original expression. (Thanks @JeffMercado!)
Upvotes: 1