Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to encode bytes in JSON? json.dumps() throwing a TypeError

I am trying to encode a dictionary containing a string of bytes with json, and getting a is not JSON serializable error:

import base64 import json  data = {} encoded = base64.b64encode(b'data to be encoded') data['bytes'] = encoded  print(json.dumps(data)) 

The error I get:

TypeError: b'ZGF0YSB0byBiZSBlbmNvZGVk\n' is not JSON serializable 

How can I correctly encode my dictionary containing bytes with JSON?

like image 609
Fanta Avatar asked Oct 12 '16 13:10

Fanta


People also ask

What is JSON dumps () method?

The dump() method is used when the Python objects have to be stored in a file. The dumps() is used when the objects are required to be in string format and is used for parsing, printing, etc, . The dump() needs the json file name in which the output has to be stored as an argument.

What is JSON dump and dumps?

1. json. dump() method used to write Python serialized object as JSON formatted data into a file. json. dumps() method is used to encodes any Python object into JSON formatted String.


1 Answers

The JSON format only supports unicode strings. Since base64.b64encode encodes bytes to ASCII-only bytes, you can use that codec to decode the data:

import base64  encoded = base64.b64encode(b'data to be encoded')  # b'ZGF0YSB0byBiZSBlbmNvZGVk' (notice the "b") data['bytes'] = encoded.decode('ascii')            # 'ZGF0YSB0byBiZSBlbmNvZGVk' 

Note that to get the original data back you don't need to re-encode it to bytes because b64decode handles ASCII-only strings as well as bytes:

decoded = base64.b64decode(data['bytes'])  # b'data to be encoded' 
like image 93
Martijn Pieters Avatar answered Sep 23 '22 09:09

Martijn Pieters