user3441187
user3441187

Reputation: 335

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 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?

Upvotes: 31

Views: 52787

Answers (2)

Pankaj Mandale
Pankaj Mandale

Reputation: 616

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.

Upvotes: 10

Saucier
Saucier

Reputation: 4370

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.

Upvotes: 40

Related Questions