Madura Dissanayake
Madura Dissanayake

Reputation: 8759

How to separate JSON keys and values in shell using jq

I have a json output file which contains the following output. I'm trying to get the value for the "status" keys but it did give me answer as null all the time using the following command.

cat output.json | jq -r ".status"

output.json

{
  "executions": [
    {
      "executionArn": "execution:job-execution:1ddb41e1-0d71-4dde-9cd0-d55119be334d",
      "stateMachineArn": "stateMachine:job-execution",
      "name": "jjfjnsldfnowef",
      "status": "RUNNING",
      "startDate": 1609918173.79
    },
    {
      "executionArn": "execution:job-execution:c07927bc-d871-4996-a58a-f9c89cbd351f",
      "stateMachineArn": "stateMachine:job-execution",
      "name": "c07927bc-23jjfnjfjs",
      "status": "RUNNING",
      "startDate": 1609918124.174
    }
  ]
}

Can anyone help me to get that expected output below.

"status": "RUNNING"
"status": "RUNNING"

Upvotes: 1

Views: 274

Answers (1)

piojo
piojo

Reputation: 6723

You can get something pretty close with this code:

cat output.json | jq "{status: .executions[].status}"

Explanation: cat output.json | jq ".executions[].status" would filter all elements of executions for the "status" field, and return the values as a list. But you don't want a list, you want a collection of field/value pairs. You can make that manually by creating an object with {key: any query that creates a value}.

The output is:

{
  "status": "RUNNING"
}
{
  "status": "RUNNING"
}

If you want to build strings instead (to get almost the exact output you asked for), you can do it by creating a formatted string with your "status: " text, also containing the query that will be interpolated.

cat output.json | jq '@text "status: \(.executions[].status)"'

The output is:

"status: RUNNING"
"status: RUNNING"

Upvotes: 1

Related Questions