codeofnode
codeofnode

Reputation: 18629

Why jq array returns length is greater than actual no of array items

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

Answers (1)

janos
janos

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

Related Questions