I am sending binary data in a post request as part of a request. I have a dictionary that looks like this:
data = {"foo": "bar", "bar": b'foo'}
When I try to json.dumps
this dictionary, I get the following exception:
TypeError: b'foo' is not JSON serializable
This worked fine in Python 2.7. What do I have to do to json encode this data?
The Python "TypeError: the JSON object must be str, bytes or bytearray, not dict" occurs when we pass a dictionary to the json. loads() method. To solve the error, remove the call to json. loads() and use the 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.
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.
In Python 3, they removed byte
support in json
. (Source: https://bugs.python.org/issue10976).
A possible workaround is:
import json
data = {"foo": "bar", "bar": b"foo"}
# decode the `byte` into a unicode `str`
data["bar"] = data["bar"].decode("utf8")
# `data` now contains
#
# {'bar': 'foo', 'foo': 'bar'}
#
# `json_encoded_data` contains
#
# '{"bar": "foo", "foo": "bar"}'
#
json_encoded_data = json.dumps(data)
# `json_decoded_data` contains
#
# {'bar': 'foo', 'foo': 'bar'}
#
json_decoded_data = json.loads(data)
# `data` now contains
#
# {'bar': b'foo', 'foo': 'bar'}
#
data["bar"] = data["bar"].encode("utf8")
If you don't have a constraint of using json
, you might consider using bson
(Binary JSON):
import bson
data = {"foo": "bar", "bar": b"foo"}
# `bson_encoded_data` contains
#
# b'\x1f\x00\x00\x00\x05bar\x00\x03\x00\x00\x00\x00foo\x02foo\x00\x04\x00\x00\x00bar\x00\x00'
#
bson_encoded_data = bson.BSON.encode(data)
# `bson_decoded_data` contains
#
# {'bar': b'foo', 'foo': 'bar'}
#
bson_decoded_data = bson.BSON.decode(data)
With Json module you cannot dump bytes. A suitable alternative is to use Simple Json Module.
To Install Simple json:
pip3 install simplejson
Code:
import simplejson as json
data = {"foo": "bar", "bar": b"foo"}
json.dumps(data)
Hopefully you won't get the error now!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With