Serialize objects to JSON even when Python doesn’t want to

Originally posted on 2022-01-03

Have you experienced the dreaded is not JSON serializable error when using json.dumps in Python? Well, if you’re OK with omitting data that isn’t serializable here’s the quick fix that I use:

def serialize(data):
    return json.dumps(data, default=lambda o: '<not serializable>').encode('utf-8')

Full disclosure: I found this on Stack Overflow at some point so I can’t take credit for writing it.