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
After
.parent.innerList[] |
your context isn’t the root anymore. AccessrootElement
outside the iteration:Demo
Using a jq variable in this and similar cases makes for an easy-to-read solution:
Or, if you want the .rootElement key to appear first in the outermost object, change the last line above to: