Home > Blockchain >  Append a string to the output of jq
Append a string to the output of jq

Time:07-21

I have a bash script that parses a json file using jq command

{
  "appsol": {
    "test": {
      "repository": "https://github.com/App/test.git",
      "test-broker": {
        "commit": ""
        "image-tag": "master-v2",
        "image-name": "test-broker",
        "image-repository": "us.gcr.io",
        "image-namespace": "ap-cloud"
      },
      "test-service-provider": {
        "commit": "",
        "image-tag": "master-v2",
        "image-name": "test-service-provider",
        "image-repository": "us.gcr.io",
        "image-namespace": "ap-cloud"
      }
    }
  }
}

Using jq command I parse the values of image-tag and image-name keys (.. | objects | select(has("image-name")) | (."image-name", ."image-tag"))

jq -r --arg prefix "_IMAGE " '
   $prefix   (.. | objects | select(has("image-name")) | (."image-name", ."image-tag"))
' image-data.json

I am appending a string _IMAGE for the value parsed from the jq command using the above snippet and its output is

_IMAGE test-broker
_IMAGE master-v2
_IMAGE test-service-provider
_IMAGE master-v2

What changes should I make in the jq command so that it appends _IMAGE for value parsed from image-name key and _VERSION for value parsed from image-tag key. Output should look something like this:

_IMAGE test-broker
_VERSION master-v2
_IMAGE test-service-provider
_VERSION master-v2

CodePudding user response:

You can just define another prefix and reorder:

jq -r --arg prefix1 "_IMAGE " --arg prefix2 "_VERSION "  '
  .. | objects | select(has("image-name")) |
  ($prefix1   ."image-name", $prefix2   ."image-tag")
' image-data.json
  • Related