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 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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With