在写入CSV时,将JSON的键附加为csv列

时间:2014-06-09 23:27:21

标签: python json converter

我是Python新手, 我需要将以下JSON格式转换为csv。

{
"2efbc1d": ["ad5460", 32.8963, -84.3213, 74, 39000, 596, 10048, 8444, "B737", "N958WN", 1395360005, "", "", "", 0, 0, "", 0], 

"2efbaa6": ["a1d0a3", 40.3773, -74.2731, 44, 7100, 249, 8450, 8444, "E170", "N216JQ", 1395360005, "", "", "", 0, 0, "592660", 0],

"2ef8db0": ["a8aa73", 40.8801, -73.4095, 46, 27075, 487, 22372, 8444, "B752", "N658AA", 1395360005, "MIA", "BOS", "AA2412", 0, 0, "AAL2412", 0]
 }

它的关键:[数组]格式。

我修改的代码从堆栈溢出中获取并修改后将数组写为csv,但我需要将该键添加为第一列。

我的代码在这里

import json
import csv

with open("data.json") as file:
data = json.load(file)

with open("data.csv", "w") as file:
csv_file = csv.writer(file)
print( data.keys())
newlist = list()
for i in data.keys():
   newlist.append(i)
print(newlist[1])

cnt = 0 #len(newlist)-
for item in data:
    csv_file.writerow(  data[newlist[cnt]])
    cnt = cnt+1 

任何帮助表示感谢。

2 个答案:

答案 0 :(得分:0)

您需要创建一个列表[key, val0, val1, val2, ...]。可能最直接的方式是:

for key, value in data.items():
    l = [key]
    l.extend(values)
    csv_file.writerow(l)

答案 1 :(得分:0)

您可以将JSON转换为列表列表,然后像您一样使用csv模块“writerow。这就是我的意思:

data = {'2efbc1d': ['ad5460', 32.8963, -84.3213, 74, 39000, 596, 10048, 8444, 'B737', 'N958WN', 1395360005, '', '', '', 0, 0, '', 0], '2ef8db0': ['a8aa73', 40.8801, -73.4095, 46, 27075, 487, 22372, 8444, 'B752', 'N658AA', 1395360005, 'MIA', 'BOS', 'AA2412', 0, 0, 'AAL2412', 0], '2efbaa6': ['a1d0a3', 40.3773, -74.2731, 44, 7100, 249, 8450, 8444, 'E170', 'N216JQ', 1395360005, '', '', '', 0, 0, '592660', 0]}

rows = []
for k, v in data.items():
    new_list = [k]
    new_list.extend(v)
    rows.append(new_list)

print rows

这会给你:

['2efbc1d', 'ad5460', 32.8963, -84.3213, 74, 39000, 596, 10048, 8444, 'B737', 'N958WN', 1395360005, '', '', '', 0, 0, '', 0]
['2efbaa6', 'a1d0a3', 40.3773, -74.2731, 44, 7100, 249, 8450, 8444, 'E170', 'N216JQ', 1395360005, '', '', '', 0, 0, '592660', 0]
['2ef8db0', 'a8aa73', 40.8801, -73.4095, 46, 27075, 487, 22372, 8444, 'B752', 'N658AA', 1395360005, 'MIA', 'BOS', 'AA2412', 0, 0, 'AAL2412', 0]

现在对writerow的每个元素(子列表)执行rows。或者正如jonrshrape的回答所示,在创建时写下new_list,然后取消rows列表列表。