jsonjq

Using jq to replace the value of a JSON field is not working correctly


I have a template JSON file like this:

[
  {
    "fields": [
      {
        "name": "body_t",
        "value": "TEST"
      }
    ],
    "id": "abc123"
  }
]

I need to replace the "value" of the "body_t" (which is set to TEST in the template).

jq '.[].fields[] | select(.name == "body_t") | .value = "'"TEST"'"' template.json

I receive back the following error:

Cannot index string with string "fields"

What am I doing wrong here?


Solution

  • If you want to keep the original structure, I'd use:

    map(.fields[] |= (select(.name == "body_t").value |= "Some value"))
    

    [
      {
        "fields": [
          {
            "name": "body_t",
            "value": "Some value"
          }
        ],
        "id": "abc123"
      }
    ]
    

    JqPlay Demo