且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在python中将JSON列表转换为CSV文件

更新时间:2023-01-18 18:04:27

csv.writer用于列表列表或元组列表.因此,将其用于字典列表会触发预期序列"错误.而是使用csv.DictWriter如下:

csv.writer is made for lists of lists or lists of tuples. So using it for list of dicts triggers a "sequence expected" error. Instead, use csv.DictWriter as follows:

import csv

data=[{u'TEMP': 30, u'LIGHT': 315, u'HUMIDITY': 30.9, u'SOURCE': u'arduino_1', u'PLACE': u'kitchen', u'time': u'2016-12-31T11:18:38.822822913Z'},
{u'TEMP': 31, u'LIGHT': 325.5, u'HUMIDITY': 31.93, u'SOURCE': u'arduino_1', u'PLACE': u'garage', u'time': u'2016-12-31T11:18:39.919019993Z'},
{u'TEMP': 32, u'LIGHT': 336, u'HUMIDITY': 32.96, u'SOURCE': u'arduino_1', u'PLACE': u'living_room', u'time': u'2016-12-31T11:18:41.014792508Z'},
{u'TEMP': 33, u'LIGHT': 346.5, u'HUMIDITY': 33.99, u'SOURCE': u'arduino_1', u'PLACE': u'basement', u'time': u'2016-12-31T11:18:42.11100167Z'}]

with open("output.csv","w",newline="") as f:  # python 2: open("output.csv","wb")
    title = "time,SOURCE,PLACE,TEMP,LIGHT,HUMIDITY".split(",") # quick hack
    cw = csv.DictWriter(f,title,delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
    cw.writeheader()
    cw.writerows(data)

固定标题顺序是通过重新使用您提供的顺序来完成的(其他顺序是词典顺序,而不是您想要的顺序).

fixing title order is done by reusing the order you provided (else order is the dictionary order, not the one you want).

写标题以获得标题,然后在词典列表中使用writerows写入数据.

Write the header to get the title, then use writerows on the list of dictionaries to write the data.

输出:

time,SOURCE,PLACE,TEMP,LIGHT,HUMIDITY
2016-12-31T11:18:38.822822913Z,arduino_1,kitchen,30,315,30.9
2016-12-31T11:18:39.919019993Z,arduino_1,garage,31,325.5,31.93
2016-12-31T11:18:41.014792508Z,arduino_1,living_room,32,336,32.96
2016-12-31T11:18:42.11100167Z,arduino_1,basement,33,346.5,33.99

请注意,担心您的u前缀不会出现在结果中.只是代表人物而已.

note that the u prefix that was worrying you doesn't appear in the result. It's just a representation character.