Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Serialize object to json

So i have the following objects:

import os
import sys
import json

class ComplexEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, P):
            return json.dumps(obj.__dict__)
        # Let the base class default method raise the TypeError
        return json.JSONEncoder.default(self, obj)

class P(object):
    def __init__(self):
        self.name = "Unknown"
        self.id = 1
        self.lst = []

    def showName(self):
        print(self.name)
        for item in self.lst:
            item.showName()

    def add(self, p):
        self.lst.append(p)

    def serialize(self):
        return json.dumps(self, cls=ComplexEncoder)

class PFirst(P):
    def __init__(self):
        P.__init__(self)
        self.name = "First"
        self.id = 2

p1 = PFirst()
p1.showName()

p = P()
p.add(p1)
p.showName()

print(p.serialize())

I want to make a json which reprezents the attributes of object p but i receive the following error:

TypeError: <__main__.PFirst object at 0x000002AA287F1438> is not JSON serializable

Can someone please help me?

like image 526
Martin Rezyne Avatar asked Apr 08 '17 15:04

Martin Rezyne


People also ask

How do you serialize an object in Python?

Using Python's Pickle Library Afterward, to serialize a Python object such as a dictionary and store the byte stream as a file, we can use pickle's dump() method. test_dict = {"Hello": "World!"} The byte stream representing test_dict is now stored in the file “ test. pickle ”!

How do you serialize and deserialize a JSON object in Python?

For serializing and deserializing of JSON objects Python “__dict__” can be used. There is the __dict__ on any Python object, which is a dictionary used to store an object's (writable) attributes. We can use that for working with JSON, and that works well.

How do I save a Python object to JSON?

To dump a Python object to JSON string, you can use the json. dumps() method of the built-in json module. The json. dump() paired method (without the "s") converts the Python object to JSON string and writes it to a file.

What is JSON serialization Python?

Serialization is the process of transforming objects of complex data types (custom-defined classes, object-relational mappers, datetime, etc.) to native data types so that they can then be easily converted to JSON notation.


1 Answers

        return json.dumps(obj.__dict__)

You are calling json.dumps with the default encoder again, which surely don't know how to deal with P objects. If you do want to call json.dumps, use:

        return json.dumps(obj.__dict__, cls=type(self))
#                                     ^~~~~~~~~~~~~~~~

However! If the print the result, we see the result is double-encoded as a string:

"{\"name\": \"Unknown\", \"id\": 1, \"lst\": [\"{\\\"name\\\": \\\"First\\\", \\\"id\\\": 2, \\\"lst\\\": []}\"]}"

If you check the ComplexEncoder example, and also the documentation of default(), we will note that it should return a "serializable object", not the serialized string. So you should really write:

class ComplexEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, P):
            return obj.__dict__         # <-----
        return json.JSONEncoder.default(self, obj)

Output:

{"name": "Unknown", "id": 1, "lst": [{"name": "First", "id": 2, "lst": []}]}
like image 184
kennytm Avatar answered Oct 17 '22 15:10

kennytm