Home > OS >  Add new element to existing JSON to a specific list element with jq
Add new element to existing JSON to a specific list element with jq

Time:09-28

I have an already existing json, in which I have to add a new element to a list element which has a specific key-value pair. For example:

{
  "parent": {
    "child-list": [
      {
        "usecase": "first"
      },
      {
        "usecase": "second"
      },
      {
        "usecase": "third"
      }
    ]
  }
}

So I would like to have this as result:

{
  "parent": {
    "child-list": [
      {
        "usecase": "first"
      },
      {
        "usecase": "second",
        "result": "SUCCESS"
      },
      {
        "usecase": "third"
      }
    ]
  }
}

I've tried this:

jq '.parent."child-list" | map(select(."usecase"=="second")  = { "result": "SUCCESS" })' base.json

But it prints only the 'child-list' not the whole json.

CodePudding user response:

Use |= instead of |. It updates the object rather than just taking it as next input (just like you used = not just later on).

jq '.parent."child-list" |= map(select(."usecase"=="second")  = { "result": "SUCCESS" })' base.json
  • Related