为什么赢得#python3加载这个json字符串?

时间:2016-04-22 22:15:32

标签: python json python-3.x encoding utf-8

我有一个字符串

b'{"nonce":"820346305172674795","hash":"CF9558F1AC5AA3F4F3D598BAD50D8E0FD15E536A98095C01AD1BA962BDF342D0E37CF6ED595758B3217CA1986238B10EB729D5C5EBCE1523B41328365E936DBE","encryptedMessage":"ABF47CA76B72388B3CA8F4BF95D199D02835C5AED546CC6A6A35663C312093DB05E3765A00211242770136D7F2391A2A69CCA28B4D9695","signature":"09036C211B6386AD0B1D7EDA14AE4C4C77721916C9AF48E7141049E2773098665776AA4B7CC6E12B4B5BD1FBB3B590F41C6254313BAEBA9293D87769F1A4200468747470733A2F2F3139322E3136382E312E38343A353030302F746F67676C655F646F6F722431"}'

print(str(json_string))输出

当我尝试json.loads(json_string)时,它说它不能是字节数组,必须是字符串

当我尝试json。

1 个答案:

答案 0 :(得分:4)

您需要解码字节字符串,以便json可以加载它。查看json.loads的代码,它有以下异常检查:

if not isinstance(s, str):
        raise TypeError('the JSON object must be str, not {!r}'.format(
                            s.__class__.__name__))

如果您进入解释器并进行测试,您将看到发送字节字符串时出现异常:

>>> a = b'abc'
>>> type(a)
<class 'bytes'>
>>> b = b'abc'.decode('utf-8')
>>> type(b)
<class 'str'>

因此,尝试使用json.load

致电a
>>> json.loads(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/json/__init__.py", line 312, in loads
    s.__class__.__name__))
TypeError: the JSON object must be str, not 'bytes'
>>>

因此,在这种情况下,您的解决方案是使用utf-8

进行解码
import json

data = b'{"nonce":"820346305172674795","hash":"CF9558F1AC5AA3F4F3D598BAD50D8E0FD15E536A98095C01AD1BA962BDF342D0E37CF6ED595758B3217CA1986238B10EB729D5C5EBCE1523B41328365E936DBE","encryptedMessage":"ABF47CA76B72388B3CA8F4BF95D199D02835C5AED546CC6A6A35663C312093DB05E3765A00211242770136D7F2391A2A69CCA28B4D9695","signature":"09036C211B6386AD0B1D7EDA14AE4C4C77721916C9AF48E7141049E2773098665776AA4B7CC6E12B4B5BD1FBB3B590F41C6254313BAEBA9293D87769F1A4200468747470733A2F2F3139322E3136382E312E38343A353030302F746F67676C655F646F6F722431"}'

decoded_data = data.decode('utf-8')
json_data = json.loads(decoded_data)

输出:

u'nonce': u'820346305172674795', u'hash': u'CF9558F1AC5AA3F4F3D598BAD50D8E0FD15E536A98095C01AD1BA962BDF342D0E37CF6ED595758B3217CA1986238B10EB729D5C5EBCE1523B41328365E936DBE', u'encryptedMessage': u'ABF47CA76B72388B3CA8F4BF95D199D02835C5AED546CC6A6A35663C312093DB05E3765A00211242770136D7F2391A2A69CCA28B4D9695', u'signature': u'09036C211B6386AD0B1D7EDA14AE4C4C77721916C9AF48E7141049E2773098665776AA4B7CC6E12B4B5BD1FBB3B590F41C6254313BAEBA9293D87769F1A4200468747470733A2F2F3139322E3136382E312E38343A353030302F746F67676C655F646F6F722431'}