将Python字典转换为JSON数组

目前我有这个字典,用pprint打印:

 {'AlarmExTempHum': '\x00\x00\x00\x00\x00\x00\x00\x00', 'AlarmIn': 0, 'AlarmOut': '\x00\x00', 'AlarmRain': 0, 'AlarmSoilLeaf': '\x00\x00\x00\x00', 'BarTrend': 60, 'BatteryStatus': 0, 'BatteryVolts': 4.751953125, 'CRC': 55003, 'EOL': '\n\r', 'ETDay': 0, 'ETMonth': 0, 'ETYear': 0, 'ExtraHum1': None, 'ExtraHum2': None, 'ExtraHum3': None, 'ExtraHum4': None, 'ExtraHum5': None, 'ExtraHum6': None, 'ExtraHum7': None, 'ExtraTemp1': None, 'ExtraTemp2': None, 'ExtraTemp3': None, 'ExtraTemp4': None, 'ExtraTemp5': None, 'ExtraTemp6': None, 'ExtraTemp7': None, 'ForecastIcon': 2, 'ForecastRuleNo': 122, 'HumIn': 31, 'HumOut': 94, 'LOO': 'LOO', 'LeafTemps': '\xff\xff\xff\xff', 'LeafWetness': '\xff\xff\xff\x00', 'NextRec': 37, 'PacketType': 0, 'Pressure': 995.9363359295631, 'RainDay': 0.0, 'RainMonth': 0.0, 'RainRate': 0.0, 'RainStorm': 0.0, 'RainYear': 2.8, 'SoilMoist': '\xff\xff\xff\xff', 'SoilTemps': '\xff\xff\xff\xff', 'SolarRad': None, 'StormStartDate': '2127-15-31', 'SunRise': 849, 'SunSet': 1611, 'TempIn': 21.38888888888889, 'TempOut': 0.8888888888888897, 'UV': None, 'WindDir': 219, 'WindSpeed': 3.6, 'WindSpeed10Min': 3.6} 

当我这样做:

 import json d = (my dictionary above) jsonarray = json.dumps(d) 

我得到这个错误: 'utf8' codec can't decode byte 0xff in position 0: invalid start byte

如果你在你的json中使用非打印符号,那么添加ensure_ascii=Falsedumps调用。

 >>> json.dumps(your_data, ensure_ascii=False) 

如果ensure_ascii为false,那么返回值将是一个unicode实例,受到普通Python strunicode强制规则的约束,而不是转义为ASCII str

ensure_ascii = False确实只是将问题推迟到解码阶段:

 >>> dict2 = {'LeafTemps': '\xff\xff\xff\xff',} >>> json1 = json.dumps(dict2, ensure_ascii=False) >>> print(json1) {"LeafTemps": "    "} >>> json.loads(json1) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.7/json/__init__.py", line 328, in loads return _default_decoder.decode(s) File "/usr/lib/python2.7/json/decoder.py", line 365, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/usr/lib/python2.7/json/decoder.py", line 381, in raw_decode obj, end = self.scan_once(s, idx) UnicodeDecodeError: 'utf8' codec can't decode byte 0xff in position 0: invalid start byte 

最终,您不能将原始字节存储在JSON文档中,因此您需要使用一些方法将任意字节序列明确地编码为ASCIIstring,例如base64。

 >>> import json >>> from base64 import b64encode, b64decode >>> my_dict = {'LeafTemps': '\xff\xff\xff\xff',} >>> my_dict['LeafTemps'] = b64encode(my_dict['LeafTemps']) >>> json.dumps(my_dict) '{"LeafTemps": "/////w=="}' >>> json.loads(json.dumps(my_dict)) {u'LeafTemps': u'/////w=='} >>> new_dict = json.loads(json.dumps(my_dict)) >>> new_dict['LeafTemps'] = b64decode(new_dict['LeafTemps']) >>> print new_dict {u'LeafTemps': '\xff\xff\xff\xff'} 

如果您使用Python 2,请不要忘记在脚本的第一行添加UTF-8文件编码注释。

 # -*- coding: UTF-8 -*- 

这将解决一些Unicode问题,让你的生活更轻松。

我使用的一个可能的解决scheme是使用python3。 它似乎解决了很多的UTF问题。

对不起,对于迟到的答案,但它可能会帮助未来的人。

例如,

 #!/usr/bin/env python3 import json # your code follows