I have a JSON which looks like this
{
"orders": [
{
"order": [
{
"items": [
{
"name": "Item 1",
"id": [],
"type": [
{
"name": "Color",
"value": [
{
"value": "blue"
}
]
},
{
"name": "model",
"value": [
{
"value": "Stereo"
}
]
}
]
}
]
},
{
"items": [
{
"name": "Item 2",
"id": [],
"type": [
{
"name": "Color",
"value": [
{
"value": "Yellow"
}
]
},
{
"name": "model",
"value": [
{
"value": "NewModel"
}
]
}
]
}
]
}
],
"id": "715874"
},
{
"order": [
{
"items": [
{
"name": "Item 6",
"id": [],
"type": [
{
"name": "Range",
"value": [
{
"value": "10"
}
]
},
{
"name": "Type",
"value": [
{
"value": "AllRegion"
}
]
}
]
}
]
},
{
"items": [
{
"name": "Item 4",
"id": [],
"type": [
{
"name": "Color",
"value": [
{
"value": "Yellow"
}
]
},
{
"name": "model",
"value": [
{
"value": "OldModel"
}
]
}
]
}
]
}
],
"id": "715875"
}
]
}
I am trying to convert to this format
{
"order": [
{
"items": [
{
"name": "Item 1",
"type": {
"Color": "blue",
"model": "Stereo"
}
},
{
"name": "Item 2",
"type": {
"Color": "Yellow",
"model": "NewModel"
}
}
],
"id": "715874"
},
{
"items": [
{
"name": "Item 6",
"type": {
"Color": "blue",
"Type": "AllRegion"
}
},
{
"name": "Item 4",
"type": {
"Color": "Yellow",
"model": "OldModel"
}
}
],
"id": "715875"
}
]
}
I tried using queries like this, not able to achieve the format i am looking for..
.orders[] | { orders : [ .order[] |{ .order[].items : .], id : .id } ]}
{ orders : [ .orders[] |{ order : [.items[].name[] ], id : .id } ]}
Please help. thanks in Advance. I am parsing this in Python, if any other Lib can parse this similar to JQ thats also helpfull.
2
Answers
Using jq, just define for each field what it should iterate over and collect:
Demo
I would do it with the json module. Suppose your original json is stored as
original_data
.Then you can iterate over it to construct your desired format:
.dumps
So code would be like this: