31

I have a json store in jsonFile

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

I have code in mycode.sh:

#!/bin/bash
value=($(jq -r '.key1' jsonFile))
echo "$value"

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

Could anyone help me?

Scott Stensland
  • 26,870
  • 12
  • 93
  • 104
user3441187
  • 335
  • 1
  • 3
  • 6

2 Answers2

38

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]}"
aaaa

$ echo "${value[1]}"
bbbb

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

Saucier
  • 4,200
  • 1
  • 25
  • 46
  • i tried your solution and it works on the command line. however, when I put the same code in a bash script i keep getting **syntax error near unexpected token `(**. any idea why this happens ? – hieu le Jan 11 '17 at 21:02
  • actually i solved mine :) my problem was i had spaces " " around equal sign "=" when i assign output to variable. I had sth like x = $(script). After I removed the spaces it works fine! Thanks :) – hieu le Jan 13 '17 at 00:17
  • Nice. Have a look over there for a superb reference: http://mywiki.wooledge.org/BashGuide/Parameters – Saucier Jan 13 '17 at 13:43
  • what if I want to save "aaaa bbbbb" into bash array as one element? like ("aaaa bbbbb"). I have same problem with parsing json and save two key values into array. `echo '{ "foo": "foovalue1 foovalue2", "bar": "barvalue" }'` output: "foovalue1 foovalue2" "barvalue" I want to save it to bash array as two (not three!) elements, like: `array=($(echo '{ "foo": "foovalue1 foovalue2", "bar": "barvalue" }' | jq -r '.foo, .bar'))` – sergei Feb 04 '20 at 06:48
9
local result=$(<your_json_response>)
local aws_access_key=$(jq -r '.Credentials.AccessKeyId' <<< ${result})
local aws_secret_key=$(jq -r '.Credentials.SecretAccessKey' <<< ${result})
local session_token=$(jq -r '.Credentials.SessionToken' <<< ${result})

Above code is another way to get the values from json response.

Pankaj Mandale
  • 596
  • 7
  • 15