skip to Main Content

This is my sample json

{
  "parent": {
    "rootElement": "root",
    "innerList": [
      {"id": 1, "value": "A"},
      {"id": 2, "value": "B"},
      {"id": 3, "value": "C"}
    ]
  }
}

I want a transformed json like this using jq commands

{"innerList": [
        {"id": 1, "rootElement": "root", "value": "A"
        },
        {"id": 2, "rootElement": "root", "value": "B"
        },
        {"id": 3, "rootElement": "root", "value": "C"
        }
    ],
 "rootElement": "root"
}

I tried this command but I dont get the desried output as I am not able to access the root element once I inside parsing the inner list.

jq '{rootElement: .parent.rootElement, innerList: [.parent.innerList[] | {id, value: .value, rootElement: .parent.rootElement}]}'

I get

{"innerList": [
        {"id": 1, "rootElement": null, "value": "A"
        },
        {"id": 2, "rootElement": null, "value": "B"
        },
        {"id": 3, "rootElement": null, "value": "C"
        }
    ],
 "rootElement": "root"
}

2

Answers


  1. After .parent.innerList[] | your context isn’t the root anymore. Access rootElement outside the iteration:

    .parent | .innerList[] += {rootElement}
    
    {
      "rootElement": "root",
      "innerList": [
        {
          "id": 1,
          "value": "A",
          "rootElement": "root"
        },
        {
          "id": 2,
          "value": "B",
          "rootElement": "root"
        },
        {
          "id": 3,
          "value": "C",
          "rootElement": "root"
        }
      ]
    }
    

    Demo

    Login or Signup to reply.
  2. Using a jq variable in this and similar cases makes for an easy-to-read solution:

    .parent
    | .rootElement as $rootElement
    | .innerList[] += {$rootElement}
    

    Or, if you want the .rootElement key to appear first in the outermost object, change the last line above to:

    | .innerList[] |= {$rootElement} + .
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search