admin管理员组

文章数量:1336643

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?

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?

Share Improve this question edited Nov 19, 2024 at 15:43 Gilles Quénot 186k43 gold badges231 silver badges229 bronze badges asked Nov 19, 2024 at 15:40 Terry Chambers - OnixTerry Chambers - Onix 5973 silver badges10 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 1

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

What I would do:

$ jq '.[].fields[] | select(.name == "body_t") | .value = "TESTOS"' file
{
  "name": "body_t",
  "value": "TESTOS"
}

本文标签: Using jq to replace the value of a JSON field is not working correctlyStack Overflow