Home > Enterprise >  Updating Nested JSON Array with new key and value from another key
Updating Nested JSON Array with new key and value from another key

Time:11-14

I have have a JSON file where I have IDs with tasks. Some tasks can be empty. I want to put the ID into the tasks where tasks are not empty.

[
  {
    "id": 1961126,
    "tasks": [
      {
        "id": 70340700,
        "title": "Test1",
      },
      {
        "id": 69801130,
        "title": "Test15A",
      }
    ]
  },
  {
    "id": 1961126,
    "tasks": []
  }           
]  

I would like to get the tasks array updated to look like

[
  {
    "id": 1961126,
    "tasks": [
      {
        **"sId":1961126,**
        "id": 70340700,
        "title": "Test1",
      },
      {
        **"sId":1961126,**
        "id": 69801130,
        "title": "Test15A",
      }
    ]
  },
  {
    "id": 1961126,
    "tasks": []
  }           
] 

I can't figure out how to get the id from the object into the nested array. Here is what I have come up with

jq 'map(.tasks[0]|select( . != null )|.sId = .id)' file.json

This is only pulling in the same id. I have tired to put in [].id but I get a error Cannot index number with string "id". I am still learning how to deal with nested arrays and objects.

CodePudding user response:

Save the ID in a variable and add it as a new field to each array member.

 jq 'map(.id as $sId | .tasks[]  = {$sId})' file.json

Demo

Note #1: Get rid of the final , within each object (see the Demo), as it's not proper JSON.

Note #2: Object fields generally have no order, but if you want to have the propagated ID shown first, as seen in your expected output, you could try to replace = {$sId} (which by itself is shorthand for |= . {$sId}) with |= {$sId} . to flip the order of generation (Demo). Although there is no guarantee that it stays that way with further processing.

  • Related