[英]Unpack a list of nested dictionaries and convert to CSV
I am trying to write to CSV a JSON that produces a list of nested dictionnaries as follows: 我正在尝试将生成嵌套字典列表的JSON写到CSV,如下所示:
[{'spam': 'xxxx',
'egg': 'yyyy',
'line_items': [{'description': 'hhh',
'amount': 'iii'},
{'description': 'jjj',
'amount': 'kkk'}],
'bacon': 'zzzz'}]
I wrote the following code (being still very new to Python): 我编写了以下代码(对Python来说仍然很新):
import csv
jsonData = json.loads(r.text)
keys = list(jsonData[0].keys())
with open(filePathCsv, 'w') as csvfile:
w = csv.DictWriter(csvfile, keys)
w.writeheader()
w.writerows(jsonData)
This produces the following: 这将产生以下结果:
What I need to achieve is this: 我需要实现的是:
where each nested line item produces a new row. 每个嵌套的订单项都会产生一个新行。
I imagine the best way to achieve this is to unpack my list of nested dictionnaries to a simple list of dictionnaries, like so: 我想实现此目的的最佳方法是将嵌套词典列表解压缩为简单词典列表,如下所示:
[{'spam': 'xxxx',
'egg': 'yyyy',
'description': 'hhh',
'amount': 'iii',
'bacon': 'zzzz'},
{'spam': 'xxxx',
'egg': 'yyyy',
'description': 'jjj',
'amount': 'kkk',
'bacon': 'zzzz'}]
But I am at a loss as to how to achieve this. 但是我对如何实现这一目标感到茫然。
Or perhaps there is another way to achieve my expected result? 也许还有另一种方式可以达到我的预期结果?
Or perhaps there is another way to achieve my expected result?
也许还有另一种方式可以达到我的预期结果?
If you use pandas
, there's a one-liner for this, using json_normalize
: 如果您使用
pandas
,那么可以使用json_normalize
来实现此json_normalize
:
import pandas as pd
data = [{'spam': 'xxxx',
'egg': 'yyyy',
'line_items': [{'description': 'hhh',
'amount': 'iii'},
{'description': 'jjj',
'amount': 'kkk'}],
'bacon': 'zzzz'}]
df = pd.io.json.json_normalize(data, record_path=['line_items'],
meta=['spam', 'egg','bacon'])
df
amount description egg spam bacon
0 iii hhh yyyy xxxx zzzz
1 kkk jjj yyyy xxxx zzzz
df.to_csv('out.csv')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.