Home > Blockchain >  Find a replace a value in a JSON array based on a property value with JQ
Find a replace a value in a JSON array based on a property value with JQ

Time:06-16

I have the following json:

{
  "configs": [
    {
      "configName": "config1",
      "configTarget": "/app/appsettings.json",
      "uid": "0",
      "gid": "0",
      "mode": 292
    },
    {
      "configName": "config2",
      "configTarget": "/app/appsettings.json",
      "uid": "0",
      "gid": "0",
      "mode": 292
    }
  ]
}

And I want to change the value of configName which currently has a value of config1.

I know I can do

.configs[0].configName = "foo"

But I don't want to rely on the position in the array of the one I want to change, how can I find that and then set the value?

CodePudding user response:

.configs |= map(select(.configName == "config1").configName |= "foo-bar")
  1. Update .configs (|=)
  2. Map over each object in the array
  3. Filter (select()) the desired object
  4. Update .configName

Result:

{
  "configs": [
    {
      "configName": "foo-bar",
      "configTarget": "/app/appsettings.json",
      "uid": "0",
      "gid": "0",
      "mode": 292
    },
    {
      "configName": "config2",
      "configTarget": "/app/appsettings.json",
      "uid": "0",
      "gid": "0",
      "mode": 292
    }
  ]
}

Demo

  • Related