Home > Net >  find and replace in json file using jq filter
find and replace in json file using jq filter

Time:07-08

I've below json file env.json and I want to search for "[\"res\",\"q3\"]" and replace it with a variable var1 value "[\"res\"]"

{
  "idsb": "marqd",
  "data": {
    "name": "bcon-dv-alert"
  },
  "ingress": {
    "args": {
      "params": [
        {
          "name": "spt",
          "value": "cld"
        },
        {
          "name": "scv",
          "value": "sdv"
        },
        {
          "name": "scr",
          "value": "ord"
        }
        {
          "name": "srm",
          "value": "[\"res\",\"q3\"]"
        },
        {
          "name": "tgo",
          "value": "pbc"
        }
      ]
    },
    "wfr": {
      "name": "t-r-e"
    },
    "snm": "as-r"
  }
}

I tried the below way but it's not working

var1="[\"res\"]"

jq '.ingress.args.params[] | select(.name=="srm").value |= ["'${var1}'"]' env.json

where am making mistake? what's the right way to do it?

The final result will be

{
  "idsb": "marqd",
  "data": {
    "name": "bcon-dv-alert"
  },
  "ingress": {
    "args": {
      "params": [
        {
          "name": "spt",
          "value": "cld"
        },
        {
          "name": "scv",
          "value": "sdv"
        },
        {
          "name": "scr",
          "value": "ord"
        }
        {
          "name": "srm",
          "value": "[\"res\"]"
        },
        {
          "name": "tgo",
          "value": "pbc"
        }
      ]
    },
    "wfr": {
      "name": "t-r-e"
    },
    "snm": "as-r"
  }
}

CodePudding user response:

Since you want to update ingress, and not return only the result of the loops, use:

.ingress.args.params |= map(select(.name=="srm").value |= "new-value")

Try it online

  • Related