2013-02-02 23 views
64

使用pprint轉換Python字典,以JSON數組目前,我有這個詞典,印刷

{'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

+0

你的問題在於:'\ xff' –

回答

119

如果您在您的json中使用非打印符號都可以,然後將ensure_ascii=False添加到dumps調用中。

>>> json.dumps(your_data, ensure_ascii=False) 
​​3210
+0

將'indent = n'添加到漂亮打印的選項中,其中'n'是要縮進的空格數 – RTF

12

ensure_ascii =假真的只能推遲問題的解碼階段:

>>> 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文件,所以您需要使用一些將任意字節序列明確編碼爲ASCII字符串的方法 - 比如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'} 
+0

您可以在json中傳遞任意二進制數據(效率低下)使用'latin1'編碼](http://ideone.com/VrOtxm) – jfs

+1

你可以,我想,但json被設計/打算使用utf-8。 –

+2

@ J.F.Sebastian:的確,與'b64encode'相比,_very_效率低下。例如,對於256字符串s =''.join(xr(256))中的i,chr(i)),len(json.dumps(b64encode(s)))== 346' vs'len (json.dumps(s.decode('latin1')))== 1045'。 – martineau

2

我使用的一種可能的解決方案是使用python3。它似乎解決了很多utf問題。

對不起,對於遲來的答案,但它可能會幫助未來的人。

例如,

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

當然,你是該死的,Python 3解決了許多編碼問題。但這不是這個問題的答案。它顯式標記爲python-2.7。所以你說的是這樣的:你的舊車沒有內置的真空吸塵器。所以請購買一輛新車,而不是在您的舊車中添加吸塵器。 – colidyre

7

如果您使用Python 2,不要忘記添加你的腳本的第一行中的UTF-8編碼的文件註釋。

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

這將解決一些Unicode問題,讓您的生活更輕鬆。