Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jq error when looping through array: Cannot index array with string "<key>"

I'm tryng to iterate over all element contain in the all index. Here is my json string :

{  
   "all":[  
      {  
            "id":"51a"
      },
      {  
            "id":"52b"
      },
      {  
            "id":"53c"
      }
    ]
}

I have tried to iterate with jq :

for id in $(jq '.all.id | keys | .[]' <<< "$json"); do
    echo "$id"
done

But I get this following error :

jq: error (at :9): Cannot index array with string "id"

I expect to get the following output :

51a
52b
53c
like image 825
executable Avatar asked Oct 29 '25 02:10

executable


2 Answers

Like that:

for id in $(jq -r '.all[].id' <<< "$json"); do
    echo "$id"
done

Notice that -r option has to be used if you want to remove double quotes:

 ·   --raw-output / -r:

       With this option, if the filter´s result is a string then
       it will be written directly to standard output rather than
       being formatted as a JSON string with quotes. This can be
       useful for making jq filters talk to non-JSON-based
       systems.

The entire script could look like that:

#!/usr/bin/env bash

json='{  
   "all":[  
      {  
            "id":"51a"
      },
      {  
            "id":"52b"
      },
      {  
            "id":"53c"
      }
    ]
}'

for id in $(jq -r '.all[].id' <<< "$json"); do
    echo "$id"
done

But as noted in the comments, for x in $(...) is an antipattern and should not be used: https://mywiki.wooledge.org/DontReadLinesWithFor.

To assign two indices to 2 separate variables:

#!/usr/bin/env bash

json='{
   "all":[
      {
            "id":"51a",
            "name":"Steve"
      },
      {
            "id":"52b",
            "name":"Phoebe"
      },
      {
            "id":"53c",
            "name":"Dino"
      }
    ]
}'

jq -r '.all[] | .id + " " + .name' <<< "$json" |
    while read -r id name; do
        echo id: "$id"
        echo name: "$name"
    done
like image 192
Arkadiusz Drabczyk Avatar answered Oct 30 '25 16:10

Arkadiusz Drabczyk


and here's an alternative solution based on a walk-path unix tool for JSON: jtc:

bash $ for id in $(jtc -qq -w'[all][:][id]' <<< "$json"); do  echo "$id"; done
51a
52b
53c
bash $ 

PS> Disclosure: I'm the creator of the jtc tool

like image 36
Dmitry Avatar answered Oct 30 '25 17:10

Dmitry