我想通过从stdin获取数据并将其输出到stdout来将CSV转换为JSON文件。输入数据的格式有一个格式(每行),如下所示: 111117_055958,B8:27:EB:DA:EF:6D,0,B8:27:EB:8F:BA:38,192.168.1.10,171110_163200,19,0,0,562,18.7,50.1,ON,OFF,44.0,6593, 3697,-2.700629,X
我的Python代码是:
#!/usr/bin/env python
import csv, json , sys
fieldnames = ("Time","MAC_ETH","IP_ETH","MAC_WiFi","IP_WiFi","Up_time","Winsen","ADC_2","ADC_3","VOC","Temp","Humidity","Internet","Lampa_UV","CPU_temp","Amph_P1","Amph_P2","PT100","Brak",)
reader = csv.DictReader(sys.stdin, fieldnames)
for row in reader:
print(json.dumps(row, sys.stdout))
sys.stdout.write('\n')
我的输出如下:
{"ADC_2": "0", "ADC_3": "0", "Up_time": "171110_163200", "MAC_WiFi": "b8:27:eb:8f:ba:38", "CPU_temp": "44.0", "Temp": "18.7", "VOC": "562", "PT100": "-2.700629", "MAC_ETH": "b8:27:eb:da:ef:6d", "Internet": "ON", "Winsen": "19", "Humidity": "50.1", "Amph_P2": "3697", "Amph_P1": "6593", "IP_ETH": "0", "Time": "111117_055958", "Brak": "X", "Lampa_UV": "OFF", "IP_WiFi": "192.168.1.10"}
所以参数的名称和值都可以。但是,与fieldnames
值中的输入字符串和顺序相比,参数的顺序是不同的。你能告诉我我做错了吗?
我在Synology上使用Python 2.7.12。
答案 0 :(得分:1)
此问题的解决方法是使用普通csv.reader()
,然后在每行构建OrderedDict()
。然后可以将其传递给json.dumps()
以维持订单:
from collections import OrderedDict
import csv, json, sys
fieldnames = ("Time", "MAC_ETH", "IP_ETH", "MAC_WiFi", "IP_WiFi", "Up_time", "Winsen", "ADC_2", "ADC_3", "VOC", "Temp", "Humidity", "Internet", "Lampa_UV", "CPU_temp", "Amph_P1", "Amph_P2", "PT100", "Brak",)
for row in csv.reader(sys.stdin):
rowd = OrderedDict(zip(fieldnames, row))
print(json.dumps(rowd, sys.stdout))
sys.stdout.write('\n')
这会输出为:
{"Time": "111117_055958", "MAC_ETH": "b8:27:eb:da:ef:6d", "IP_ETH": "0", "MAC_WiFi": "b8:27:eb:8f:ba:38", "IP_WiFi": "192.168.1.10", "Up_time": "171110_163200", "Winsen": "19", "ADC_2": "0", "ADC_3": "0", "VOC": "562", "Temp": "18.7", "Humidity": "50.1", "Internet": "ON", "Lampa_UV": "OFF", "CPU_temp": "44.0", "Amph_P1": "6593", "Amph_P2": "3697", "PT100": "-2.700629", "Brak": "X"}
答案 1 :(得分:0)
json / dict不保留键顺序。
在python中> 3.6 dict默认支持保留密钥顺序。
但是,由于reader
有一个.fieldnames
订单,您可以执行以下操作(UNTESTED):
for row in reader:
print(json.dumps({f: row[f] for f in reader.fieldnames}, sys.stdout))
sys.stdout.write('\n')
或者只是使用您自己声明的字段名:
for row in reader:
print(json.dumps({f: row[f] for f in fieldnames}, sys.stdout))
sys.stdout.write('\n')