5

I have a huge JSON object with an array of objects inside it. I have to add key:value pair to a specific object in the array. For example, let the input object is:

{
  "a": {
    "b": [
      {
        "name": "name1",
        "value": 1,
        "param": {
          "p1": "par1"
        }
      },
      {
        "name": "name2",
        "value": 2,
        "param": {
          "p1": "par2"
        }
      },
      {
        "name": "name3",
        "value": 3,
        "param": {
          "p1": "par3"
        }
      }
    ],
    "c": 4,
    "d": 5
  }
}

Using index the modification is easy:

 jq '.a.b[0].param += {new: "QQQ"}'

But I can not be 100% sure of index. I have to specify the object with the name tag .name == "name1".

How to modify an object identified by name tag?

New contributor
Vlado B. is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.

2 Answers 2

4

IDK what the best way to do it is but this one works:

.a.b |= map(if .name == "name1" then (.new = "QQQ") else . end)
1
  • The |= is the trick I missed! Exact expression is jq '.a.b |= map(if .name == "name1" then (.param += {new: "QQQ"}) else . end)'. Thanks.
    – Vlado B.
    Commented yesterday
3

It feels natural to do the selection of the element to update using select(), and then use map() to map the selection and assignment to all elements of the b sub-array:

jq '.a.b |= map(select(.name == "name1").param += { new: "QQQ" })'  file

or, shorter

jq '.a.b |= map(select(.name == "name1").param.new = "QQQ")' file

Or, you could pick out all the param entries from the elements of the b array and update them. This would be closer to your own command that updates the first element of b unconditionally:

jq '(.a.b[] | select(.name == "name1").param) += { new: "QQQ" }'

or, shorter,

jq '(.a.b[] | select(.name == "name1").param).new = "QQQ"'  file
1
  • The second is the one I prefer +1
    – Fravadona
    Commented yesterday

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .