简体   繁体   中英

extract 2 values from JSON object and use as variables in loop using jq and bash

I am new to jq. I am trying to write a simple script that loops through a JSON file, gets two values within each object and assigns them to two separate variables I can use with a curl REST call. I see both values as output when I echo $i but how can I get value and addr as separate variables?

for i in `cat /Users/egraham/Downloads/test2  | jq .[] | jq ."value,.addr"`; do

You can do this:

jq -rc '.populator.value + " " + .populator.addr' file.json |
while read -r value addr; do
    echo do something with "$value" and "$addr"
done

If spaces or tabs or other special characters make using 'read -r' problematic, and if your shell has "readarray", then it could be used:

$ readarray -t v < <(jq -rc '.populator | (.value,.addr)' file.json)

The values would then be available as ${v[0]} and ${v[1]}

This approach is especially useful if there are more than two values of interest, or if the number of values is variable or not known beforehand.

If your shell does not have readarray , then you can still use the array-oriented approach, eg along the lines of:

i=-1; while read -r a ; do i=$((i+1)); v[$i]="$a" ; done

First:

for i in cat /Users/egraham/Downloads/test2 | jq .[] | jq .value; do echo $i done

Second:

for i in cat /Users/egraham/Downloads/test2 | jq .[] | jq .addr; do echo $i done

I don't know any way to get it without running the commands separately. I don't know AWK, but maybe it's something worth considering.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM