Matthew Darnell
Matthew Darnell

Reputation: 1365

Why won't python3 load this json string?

I have a string

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

that is the print(str(json_string)) output

when i try json.loads(json_string), it says it can't be a byte array, must be a string

When I try json.

Upvotes: 0

Views: 4368

Answers (1)

idjaw
idjaw

Reputation: 26580

You need to decode the byte string, so json can load it. Looking at the code for json.loads, it has this exception check:

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

If you go in to your interpreter and make a test, you will see the exception is expected when sending a byte string:

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

So, trying to call json.load with 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'
>>>

So, your solution in this case is to decode with 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)

Output:

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

Upvotes: 5

Related Questions