如何将具有可变长度行的平面json文件转换为csv文件?

时间:2016-05-21 18:29:49

标签: python json csv

以下是我的数据示例。

{"a":"1", "b":"2", "c":"3"},
{"a":"1", "b":"2", "c":"3", "d":"4", "e":"5"},
{"a":"1", "b":"2", "c":"3", "d":"4", "e":"5", "f":"6"}

我希望csv为:

a,b,c,d,e,f
1,2,3
1,2,3,4,5
1,2,3,4,5,6

我在线尝试了不同的转换器,但由于json文件大约是10 MB,我无法在线转换。

2 个答案:

答案 0 :(得分:1)

import csv
import json

with open('in.json') as infile:
    data = json.load(infile)

headers = set()
for row in data:
    headers.update(row.keys())

with open('out.csv', 'w') as outfile:
    writer = csv.DictWriter(outfile, headers)
    writer.writeheader()
    writer.writerows(data)

in.json

[
  {"a":"1", "b":"2", "c":"3"},
  {"a":"1", "b":"2", "c":"3", "d":"4", "e":"5"},
  {"a":"1", "b":"2", "c":"3", "d":"4", "e":"5", "f":"6"}
]

out.csv

a,c,b,e,d,f
1,3,2,,,
1,3,2,5,4,
1,3,2,5,4,6

答案 1 :(得分:0)

我想出了这个:

o = ({"a":"1", "b":"2", "c":"3"},{"a":"1", "b":"2", "c":"3", "d":"4", "e":"5"},{"a":"1", "b":"2", "c":"3", "d":"4", "e":"5", "f":"6"})

header_row = []

# gets the header
for row in o:
    for key, value in row.iteritems():
        if not key in header_row:
            header_row += key
            print(key + ',', end='')

# goes through the data
for row in o:
    for header_cell in header_row:
        if header_cell in row:
            print(row[header_cell] + ',', end='')
        else:
            print(',', end='')