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?

0

2 Answers 2

40

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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 ?
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 :)
Nice. Have a look over there for a superb reference: mywiki.wooledge.org/BashGuide/Parameters
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'))
10
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.

1 Comment

Lol. I literally came here trying to figure out how to do this for my AWS creds.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.