0

I am trying to read the json file and store the keys as bash variable and the values as variable value. For instance here is my test.json:

{
"Day":'0',
"num":'85',
"Qtr":"[20183, 20184, 20191, 20192]",
"pSize":"75"
}

I need to store the variables like this in a bash file:

    $Day=0
    $num=85
    $Qtr=[20183, 20184, 20191, 20192]
    $psize=75

I found a way to extract the value using jq, but I am unable to store the key as variable in bash

-bash-4.2$ Qtr=`jq .Qtr test.json`
-bash-4.2$ echo $Qtr
"[20183, 20184, 20191, 20192]"

Could someone please provide a snippet as to how to loop through a json file and store the key as variables and values as values?

Thank you in advance

user3605317
  • 133
  • 3
  • 10

1 Answers1

1

Would you please try the following:

#!/bin/bash

while IFS== read key value; do
    printf -v "$key" "$value"
done < <(jq -r 'to_entries|map("\(.key)=\(.value|tostring)")|.[]' test.json)

# test of the variables
echo "Day: $day"
echo "Qtr: $Qtr"
echo "num: $num"
echo "pSize: $pSize"
  • The jq command jq -r 'to_entries|map("\(.key)=\(.value|tostring)")|.[]' test.json converts the json object into key=value pairs.
  • The output of jq is fed to the while loop via the process substitution <(command).
  • The -v varname option to the printf command assigns the variable indirecly expressed with varname to the output.
tshiono
  • 21,248
  • 2
  • 14
  • 22
  • That's exactly what I wanted. it worked like a charm. Thanks a ton for showing this code snippet and I really appreciate the explanation as well. – user3605317 Mar 24 '21 at 05:05