user3441187 user3441187 - 1 year ago 74
JSON Question

get field from json and assign to variable in bash script?

I have a json store in jsonFile

"key1": "aaaa bbbbb",
"key2": "cccc ddddd"

I have code in

value=($(jq -r '.key1' jsonFile))
echo "$value"

After I run
the result is

but if I just run
jq -r '.key1' jsonFile
the result is
aaaa bbbbb

Could anyone help me?

Answer Source

With that line of code

value=($(jq -r '.key1' jsonFile))

you are assigning both values to an array. Note the outer parantheses () around the command. Thus you can access the values individually or echo the content of the entire array.

$ echo "${value[@]}"
aaaa bbbb

$ echo "${value[0]}"

$ echo "${value[1]}"

Since you echoed $value without specifying which value you want to get you only get the first value of the array.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download