0

I have a class with a child class. I'm able to serialize it into JSON using jsonpickle library. I'm trying to understand something better though. When I try to use Python's native json library, it says the object is not serializable.

I'm looking at this guide: https://www.programiz.com/python-programming/json

He's showing a class defined like this:

person_dict = {"name": "Bob",
"languages": ["English", "Fench"],
"married": True,
"age": 32
}

Which serializes OK.

print(json.dumps(person_dict))
# outputs "{"name": "Bob", "languages": ["English", "Fench"], "married": true, "age": 32}"

But I'm creating a class and instantiating an object from it.

class Purchase(object):
    def __init__(self, receipt_id, order_id):
        self.receipt_id = receipt_id
        self.order_id = order_id
        self.items = []

test = Purchase("123", "abc")
test.items.append("item1")
test.items.append("item2")

But json.dumps() doesn't work here.

print(json.dumps(test))
# outputs "TypeError: Object of type Purchase is not JSON serializable"

What fundamental am I missing here?

1
  • 2
    The example is a dict, not a class. Commented Jun 24, 2021 at 14:42

1 Answer 1

1

In your object, add a method to serialize in json:

def serialize(self):
    """JSON serializer for objects not serializable by default json code"""

    return json.dumps({'items': self.items, 'receipt_id': self.receipt_id, 'order_id': self.order_id})

and call json.dumps with the default parameter:

json.dumps(test, default=Purchase.serialize)

reference: https://docs.python.org/3/library/json.html#json.dumps

If specified, default should be a function that gets called for objects that can’t otherwise be serialized. It should return a JSON encodable version of the object or raise a TypeError. If not specified, TypeError is raised.

>>> json.dumps(test, default=Purchase.serialize)
'"{\\"items\\": [\\"item1\\", \\"item2\\"], \\"receipt_id\\": \\"123\\", \\"order_id\\": \\"abc\\"}"'
>>> d = json.loads('"{\\"items\\": [\\"item1\\", \\"item2\\"], \\"receipt_id\\": \\"123\\", \\"order_id\\": \\"abc\\"}"')
>>> d
'{"items": ["item1", "item2"], "receipt_id": "123", "order_id": "abc"}'
Sign up to request clarification or add additional context in comments.

1 Comment

This only renders the items list. Do you mean something like these options: pynative.com/make-python-class-json-serializable

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.