If you have tried to serialize an object in Python into JSON you may have come across an oblique error that mentions you’re unable to serialize it, but what does this mean?
I recently had an example whereby I needed to transfer a
dict
object through to an external API endpoint and I thought by simply using the
json.dumps()
function that I would be able to create a
json
object to send through to the API.
However, I kept getting this obnoxious error and initially couldn’t see where in my complex
dict
object what was going wrong.
It wasn’t until I looked line by line that I could see my error, I had the following in one my
dict
properties:
my_dict = {
bad_property: {a, b, c}
}
As you can see the
bad_property
had another dictionary object which didn’t have keys with corresponding values. Therefore, the
json.dumps()
function couldn’t interpret how to serialize this dictionary.
Once I properly applied the key names with their correct corresponding values I had no issues being able to serialize the dictionary using
json.dumps()
.
Hope this is able to help!