Python 사전을 JSON 배열로 변환


98

현재 다음을 사용하여 인쇄 된이 사전이 있습니다 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


당신의 문제는 여기에 있습니다 :\xff
Benjamin Toueg

답변:


167

당신이 당신의 JSON에서 인쇄 할 수없는 기호 괜찮 경우, 추가 ensure_ascii=Falsedumps호출합니다.

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

경우 ensure_ascii거짓, 다음, 반환 값은 될 것입니다 unicode일반 파이썬 예를 대상 str으로 unicode 대신 ASCII으로 탈출되는 강제 규정 str.


1
추가 indent=n고급 인쇄의 옵션에 어디 n들여 쓰기에 공간의 수는
RTF

17

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 문서에 원시 바이트를 저장할 수 없으므로 임의의 바이트 시퀀스를 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'}


1
당신은 할 수 있다고 생각하지만 json은 utf-8을 사용하도록 설계 / 의도되었습니다.
Karl Knechtel 2013

2
@JFSebastian : 사실, 매우 에 비해 비효율적 b64encode. 예를 들어, 256 문자열에 대한 s = ''.join(chr(i) for i in xrange(256)), len(json.dumps(b64encode(s))) == 346len(json.dumps(s.decode('latin1'))) == 1045.
martineau 2013

10

Python 2를 사용하는 경우 스크립트의 첫 번째 줄에 UTF-8 파일 인코딩 주석을 추가하는 것을 잊지 마십시오.

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

이렇게하면 일부 유니 코드 문제가 해결되고 생활이 더 쉬워집니다.


2

내가 사용하는 한 가지 가능한 해결책은 python3을 사용하는 것입니다. 많은 utf 문제를 해결하는 것 같습니다.

답변이 늦어서 죄송하지만 앞으로 사람들에게 도움이 될 수 있습니다.

예를 들면

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

4
물론, 당신 말이 맞습니다. Python 3는 많은 인코딩 문제를 해결했습니다. 그러나 그것은 그 질문에 대한 답이 아닙니다. python-2.7로 명시 적으로 태그가 지정됩니다. 그래서 당신이 말하는 것은 다음과 같습니다 : 당신의 오래된 차에는 내장 된 진공 청소기가 없습니다. 그러니 낡은 차에 진공 청소기를 추가하는 대신 새 차를 사주세요.
colidyre
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.