[英]How can i Convert json to csv in python
How can I convert the following json
format logs to csv
file in python
: 如何将以下json
格式的日志转换为python
csv
文件:
Json Input ( log.json
): log.json
输入( log.json
):
{"time":"14472","abc":"0","Def":[{"name":"C","value":77},{"name":"N","value":88}]}
{"time":"1447","abc":"1","Def":[{"name":"C","value":99,{"name":"N","value":0.12}]}
Csv Output: CSV输出:
time abc name value
14472 0 C 77
14472 0 N 88
1447 1 C 99
1447 1 N 0.12
Have a look at https://docs.python.org/2/library/json.html 看看https://docs.python.org/2/library/json.html
I haven't used it personally but I skimmed the docs once and it seems that it creates a dictionary for each json object and a list for each array. 我还没有亲自使用过它,但是我浏览了一下文档,似乎它为每个json对象创建了一个字典,为每个数组创建了一个列表。
Once you have that then you can get the keys for the column labels and then you can it shouldn't be a big deal to actually write the file. 一旦有了它,就可以获取列标签的键,然后可以真正写文件就没什么大不了的了。
This should work assuming the 'log.json' input file contains valid json objects: 假设'log.json'输入文件包含有效的json对象,这应该可以工作:
import csv
import json
with open('log.json', 'rb') as infile, open('output.csv', 'wb') as outfile:
fieldnames = ['time', 'abc', 'name', 'value']
writer = csv.DictWriter(outfile, fieldnames, delimiter='\t')
writer.writeheader()
for line in infile:
row = json.loads(line)
for a_def in row['Def']:
writer.writerow({'time': row['time'],
'abc': row['abc'],
'name': a_def['name'],
'value': a_def['value']})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.