Quentin Del
Quentin Del

Reputation: 1685

Write json from bash pipe with several variable interpolations

I have this output from a pipe

{
  "pipelineName": "pipelineName-AAAAQ6UFM",
  "pipelineVersion": 2,
  "stageStates": [
    {
      "stageName": "Approval",
      "inboundTransitionState": {
        "enabled": true
      },
      "actionStates": [
        {
          "actionName": "Approval",
          "latestExecution": {
            "status": "InProgress",
            "token": "aaaa-aaaa-4316-a95f-2efc51d05761"
          }
        }
      ],
      "latestExecution": {
        "pipelineExecutionId": "fc73f4cb-c5a9-44a8-8fc1-d7e50259f485",
        "status": "InProgress"
      }
    }
  ]
}

I am trying to write a json like this

{
  "pipelineName": "pipelineName-AAAAQ6UFM",
  "stageName": "Approval",
  "actionName": "Approval",
  "token": "aaaa-aaaa-4316-a95f-2efc51d05761",
  "result": {
    "status": "Approved",
    "summary": ""
  }
}

I could maybe set two variables from the pipeoutput with the read command but I don't know how to set both of them.

token

jq -r ' .stageStates[] | select(.stageName == "Approval") | .actionStates[0].latestExecution.token'

pipelineName

jq -r '.pipelineName'

Then I might be able to write the json with the jq command.

What would be the best way to do this ?

Upvotes: 0

Views: 57

Answers (2)

peak
peak

Reputation: 116870

Based on your select(.stageName == "Approval"), it would appear that you are attempting to parameterize by the "stageName", so the following might be close to what you're looking for:

"Approval" as $stage
| { pipelineName, stageName: $stage, actionName: $stage }
  + (.stageStates[] 
     | select(.stageName == $stage).actionStates[]
     | select(.actionName == $stage)
     | {token: .latestExecution.token, result: {status: "Approved", summary: ""}})

Upvotes: 1

choroba
choroba

Reputation: 241988

You can use just jq to create the json:

jq ' .stageName  = .stageStates[0].stageName
   | .actionName = .stageStates[0].actionStates[0].actionName
   | .token      = .stageStates[0].actionStates[0].latestExecution.token
   | .result     = { "status": "Approved", "summary": "" }
   | del(.stageStates, .pipelineVersion)
   ' file.json

Upvotes: 1

Related Questions