Qirohchan
Qirohchan

Reputation: 1137

reading keys shell

Now, I have done the following:

for row in $(echo "${values}" | jq -r '.[]'); do
    -jq() {
        echo ${row} | jq -r ${1}
    }
    echo $(_jq '.samplekey')
done

Here, I am unable to figure out how to extract the keys without passing in the exact keyname. Please help me, thanks!

Upvotes: 1

Views: 110

Answers (2)

RomanPerekhrest
RomanPerekhrest

Reputation: 92894

bash + jq solution:

Assuming your JSON data is saved to data.json file:

IFS=$'\t'; while read -r k v; do 
    export "$k=\"$v\""
done < <(jq -r '.data | to_entries[] | [(.key|ascii_upcase), .value] | @tsv' data.json)

Results:

$ echo "$HELLO1"
"world1"
 echo "$SAMPLEKEY"
"samplevalue"

Upvotes: 1

user7040344
user7040344

Reputation:

I try to use utility sed to extract keys list in data section. Here I assume the file name is /tmp/data.json which contains the origin json data.

sed -r -n '/"data"/,/}/{/[{}]/d;s/^[[:space:]]*"([^"]+)":.*/\U\1/g;p}' /tmp/data.json

the output is

HELLO1
SAMPLEKEY

Explanation

  1. The delimiter of json data is "data" and }, just use sed extract the lines list in them;
  2. /[{}]/d means remove lines which contain punctation { or };
  3. Set : as field delimiter in a line, extract target characters befrom :, use \U to upper all characters.

PS

If you wanna export them (export key=val), maybe you could try

sed -r -n '/"data"/,/}/{/[{}]/d;s/^[[:space:]]*"([^"]+)":[[:space:]]*"([^"]+)".*$/\1|\2/g;p}' /tmp/data.json | while IFS="|" read -r item val;do item="${item^^}"; item="${val}"; export "${item}"; echo ${item}; done

whihin while loop.

Upvotes: 0

Related Questions