Dave Michaels
Dave Michaels

Reputation: 937

Retrieving value from JSON object in bash using JQ

I have the following script:

#!/bin/bash

CONFIG_RECORDER=`aws configservice describe-configuration-recorders`
NAME=$(jq -r ‘.ConfigurationRecorders[].name’ <<<“$CONFIG_RECORDER”)
echo $NAME

I am trying to retrieve the value for name from the following JSON object:

{
"ConfigurationRecorders": [{
    "name": "default",
    "roleARN": "arn:aws:iam::xxxxxxxxxxxx:role/Config-Recorder",
    "recordingGroup": {
        "allSupported": true,
        "includeGlobalResourceTypes": true,
        "resourceTypes": []
    }
}]
}

When running the script, I am getting an error stating that jq could not open the file. That is because I am trying to pass in the result stored in a variable. How can I move past this? Below is the error:

jq: error: syntax error, unexpected INVALID_CHARACTER, expecting $end 
(Unix shell quoting issues?) at <top-level>, line 1:
‘.ConfigurationRecorders[].name’
jq: 1 compile error

Upvotes: 2

Views: 2677

Answers (1)

Udo Knop
Udo Knop

Reputation: 81

NAME=$(jq -r '.ConfigurationRecorders[].name' <<<"$CONFIG_RECORDER")

<<< is known as here-string.

-r removes the quotes in the result.

[] in the jq query is necessary as ConfigurationRecorders is a JSON array.

$( … ) is just an other form of command substitution than backticks. I prefer this one as it is more readable to me.

Upvotes: 2

Related Questions