복붙노트

[PYTHON] Python 사전을 JSON 배열로 변환

PYTHON

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'코덱은 0 위치의 바이트 0xff를 디코딩 할 수 없습니다 : 잘못된 시작 바이트

해결법

  1. ==============================

    1.json에 인쇄 할 수없는 기호가있는 것이 좋으면 덤프 호출에 ensure_ascii = False를 추가하십시오.

    json에 인쇄 할 수없는 기호가있는 것이 좋으면 덤프 호출에 ensure_ascii = False를 추가하십시오.

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

    2.ensure_ascii = False는 실제로 문제를 디코딩 단계로 전달합니다.

    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'}
    
  3. ==============================

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

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

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

    이렇게하면 유니 코드 문제가 해결되고 더 쉽게 사용할 수 있습니다.

  4. ==============================

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

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

    늦게 답변을 드려서 죄송합니다.하지만 향후 사람들에게 도움이 될 수 있습니다.

    예를 들어,

    #!/usr/bin/env python3
    import json
    # your code follows
    
  5. from https://stackoverflow.com/questions/14661051/convert-python-dictionary-to-json-array by cc-by-sa and MIT license