Cleb
Cleb

Reputation: 26027

How to JSON serialize an object and include the @property attributes while excluding functions?

There are quite a few questions related to this but non gives me exactly what I want.

Let's say I have a class like this:

import json


class MyClass:

    def __init__(self, name, some_type):

        self.name = name
        self.some_type = some_type

    @property
    def prop(self):

        return self.name + self.some_type

    def to_json(self):

        return json.dumps(
            self, default=lambda o: o.__dict__
        )


el1 = MyClass('test', '_to_json')

I would now like to get a JSON representation which includes name, some_type and also prop.

The function to_json currently only returns

{"name": "test", "some_type": "_to_json"}

so prop is missing (as well as in vars(el1)).

dir returns (as well as all the __)

'name', 'prop', 'some_type', 'to_json'

and I don't want the to_json in the list.

Is there a straightforward way to update my to_json function so that it returns

{"name": "test", "some_type": "_to_json", "prop": "test_to_json"}

?

Upvotes: 1

Views: 1017

Answers (1)

sanyassh
sanyassh

Reputation: 8540

You can find prop in __class__.__dict__:

import json


class MyClass:

    def __init__(self, name, some_type):

        self.name = name
        self.some_type = some_type

    @property
    def prop(self):

        return self.name + self.some_type

    def to_json(self):
        def get_object_dict(obj):
            d = obj.__dict__.copy()
            for key, value in obj.__class__.__dict__.items():
                if isinstance(value, property):
                    d[key] = getattr(obj, key)
            return d


        return json.dumps(
            self, default=lambda o: get_object_dict(o)
        )


el1 = MyClass('test', '_to_json')
print(el1.to_json())

Output:

{"prop": "test_to_json", "some_type": "_to_json", "name": "test"}

Upvotes: 3

Related Questions