将 Python 字典转换为 JSON 数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14661051/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:05:46  来源:igfitidea点击:

Convert Python dictionary to JSON array

pythonpython-2.7

提问by HyperDevil

Currently I have this dictionary, printed using pprint:

目前我有这本字典,打印使用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}

When I do this:

当我这样做时:

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

I get this error: 'utf8' codec can't decode byte 0xff in position 0: invalid start byte

我收到此错误: 'utf8' codec can't decode byte 0xff in position 0: invalid start byte

采纳答案by kmerenkov

If you are fine with non-printable symbols in your json, then add ensure_ascii=Falseto dumpscall.

如果您对 json 中的不可打印符号没问题,则添加ensure_ascii=Falsedumps调用。

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

If ensure_asciiis false, then the return value will be a unicodeinstance subject to normal Python strto unicodecoercion rules instead of being escaped to an ASCII str.

如果ensure_ascii是假的,那么返回值将是一个 unicode实例受到正常的Pythonstrunicode强制规则,而不是被转义为ASCII str

回答by rkday

ensure_ascii=False really only defers the issue to the decoding stage:

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

Ultimately you can't store raw bytes in a JSON document, so you'll want to use some means of unambiguously encoding a sequence of arbitrary bytes as an ASCII string - such as base64.

最终,您无法在 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'}

回答by Ralph Yozzo

One possible solution that I use is to use python3. It seems to solve many utf issues.

我使用的一种可能的解决方案是使用 python3。它似乎解决了许多 utf 问题。

Sorry for the late answer, but it may help people in the future.

抱歉回复晚了,但它可能会在将来对人们有所帮助。

For example,

例如,

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

回答by justice

If you use Python 2, don't forget to add the UTF-8 file encoding comment on the first line of your script.

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

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

This will fix some Unicode problems and make your life easier.

这将解决一些 Unicode 问题并使您的生活更轻松。