I’m generating a CSV file from JSON.
How can I get flatter JSON with the exact rows as one list of dict has?
The data in rows will be almost the same, except for a few columns which will be variate.
Example: I have
{
"transportOrder": {
"customerId":"877299" ,
"customerOrder": "155564649",
"customerReference": "reference2",
"creationDateTime": "2022-08-26T16:30:56.000Z",
"orderDetail": {
"AdditionalInfo": {
"info1": "abc",
"info2": "cds",
"name1": "Jonathan",
"name2": "Grulich",
}},
"orderLines": [
{
"amount": 7,
"code": "EUP"
},
{
"amount": 8,
"code": "ENP"
},
{
"amount": 17,
"code": "ERP"
}
]
}
}
And I want to as attached in the image:
customerId customerOrder customerReference creationDateTime info1 info2 name1 name2 amount code
877299 155564649 reference2 26.08.2022 abc cds Jonathan Grulich 7 EUP
838299 155564649 reference2 26.08.2022 abc cds Jonathan Grulich 8 ENP
838299 155564649 reference2 26.08.2022 abc cds Jonathan Grulich 17 ERP
import flatdict
data = {
"Order": {
"customerId":"877299" ,
"customerOrder": "155564649",
"customerReference": "reference2",
"creationDateTime": "2022-08-26T16:30:56.000Z",
"orderDetail": {
"AdditionalInfo": {
"info1": "abc",
"info2": "cds",
"name1": "Jonathan",
"name2": "Grulich",
}},
"orderLines": [
{
"amount": 7,
"code": "EUP"
},
{
"amount": 8,
"code": "ENP"
},
{
"amount": 17,
"code": "ERP"
}
]
}
}
flat = flatdict.FlatDict(data, delimiter='.')
result_list = []
j=0
for line in flat['Order.orderLines']:
temp = flat
temp['amount'] = line['amount']
temp['code'] = line['code']
result_list.append(temp)
print(result_list)
But I think it is not the best solution. What could it be?
2
Answers
Also I found this solution:
Output:
I would be very explicit in building such a DataFrame.
Output: