Search code examples
bashshelljqdatadog

How do I extract a Value from a Key in an Array from a json object using jq?


Im writing a bash script that needs to make two calls, the second call needs a value from the json response of the first call. However I am getting an Error when I attempt to retrieve this value.

jq: error: Could not open file ............. Invalid argument

I have checked my jq query in a browser and it works fine. Here is an example of my script.

api_key="key1"
app_key="key2"

response=$(curl -X POST \
-H 'Content-Type: application/json' \
-H "DD-API-KEY: ${api_key}" \
-H "DD-APPLICATION-KEY: ${app_key}" \
-d '{
    "tests": [
        {
            "public_id": "abc-123-xyz",
            "locations": ["aws:eu-west-2"]
         
        }
    ]
}' "https://URL")

resultId=$(jq '.results[].result_id' $response)

curl -G \
    "https://URL" \
    -H "DD-API-KEY: ${api_key}" \
    -H "DD-APPLICATION-KEY: ${app_key}" \
    -d "result_ids=[$resultId]"

and this is an example of the json response

{
    "results": [
        {
            "result_id": "1234",
            "public_id": "abc-123-xyz",
            "location": 1
        }
    ],
    "triggered_check_ids": [
        "abc-123-xyz"
    ],
    "locations": [
        {
            "is_active": boolean,
            "region": "Somewhere",
            "display_name": "A1",
            "id": 1,
            "name": "A1"
        },
        {
            "is_active": boolean,
            "region": "Somewhere else",
            "display_name": "B2",
            "id": 2,
            "name": "B2"
        }
    ]
}

Solution

  • The shell variable $response holds a JSON value, not a filename, ergo:

    resultId=$(jq '.results[].result_id' <<< "$response")