2013-02-02 45 views
64

Hiện nay tôi đã từ điển này, in sử dụng pprint:Chuyển đổi để mảng 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} 

Khi tôi làm điều này:

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

tôi nhận được lỗi này: 'utf8' codec can't decode byte 0xff in position 0: invalid start byte

+0

Sự cố của bạn nằm ở đây: '\ xff' –

Trả lời

119

Nếu bạn phù hợp với các ký hiệu không thể in được trong json của bạn, sau đó thêm ensure_ascii=False vào số dumps cuộc gọi.

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

If ensure_ascii is false, then the return value will be a unicode instance subject to normal Python str to unicode coercion rules instead of being escaped to an ASCII str .

+0

thêm' indent = n' vào các tùy chọn để in đẹp, trong đó 'n' là số không gian để thụt lề – RTF

12

ensure_ascii = False thực sự chỉ trì hoãn vấn đề cho giai đoạn giải mã:

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

Cuối cùng bạn không thể lưu trữ byte thô trong một tài liệu JSON, vì vậy bạn sẽ muốn sử dụng một số phương tiện mã hóa một cách rõ ràng một chuỗi các byte tùy ý như một chuỗi ASCII - chẳng hạn như 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

Bạn có thể chuyển dữ liệu nhị phân tùy ý (không hiệu quả) vào json [ sử dụng mã hóa 'latin1'] (http://ideone.com/VrOtxm) – jfs

+1

Bạn có thể giả sử, nhưng json được thiết kế/dự định sử dụng utf-8. –

+2

@ J.F.Sebastian: Thật vậy, _very_ không hiệu quả so với 'b64encode'. Ví dụ, đối với chuỗi ký tự 256 's = '' .join (chr (i) cho i trong xrange (256))', 'len (json.dumps (b64encode (s))) == 346' so với' len (json.dumps (s.decode ('latin1'))) == 1045'. – martineau

2

Một giải pháp có thể tôi sử dụng là sử dụng python3. Có vẻ như để giải quyết nhiều vấn đề utf.

Xin lỗi vì câu trả lời muộn, nhưng nó có thể giúp mọi người trong tương lai.

Ví dụ,

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

Chắc chắn, bạn đã đúng, Python 3 đã giải quyết được nhiều vấn đề về mã hóa. Nhưng đó không phải là câu trả lời cho câu hỏi đó. Nó được gắn thẻ rõ ràng với python-2.7. Vì vậy, những gì bạn đang nói là một cái gì đó như thế này: Không có được xây dựng trong máy hút bụi trong chiếc xe cũ của bạn. Vì vậy, hãy mua một chiếc xe mới thay vì thêm một máy hút bụi trong chiếc xe cũ của bạn. – colidyre

7

Nếu bạn sử dụng Python 2, đừng quên để thêm mã UTF-8 tập tin bình luận trên dòng đầu tiên của kịch bản của bạn.

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

Điều này sẽ khắc phục một số vấn đề về Unicode và giúp cuộc sống của bạn dễ dàng hơn.

Các vấn đề liên quan