Search code examples
pythonjsonapipython-requestsclient

Converting class instance with private variables into JSON format


I have the following code for a class. I want to convert this into a JSON so that I can send it to an API. After converting to JSON, I am getting:

{"_Test__id": 3}

I want id only in place of "_Test__id". Is there any way to do it without making id public in this class.

from json import JSONEncoder

class Test:

    def __init__(self, id=0):
        self.__id = id

    def _get_id(self):
        return self.__id

    def _set_id(self, value):
        self.__id = value

    id= property(_get_id, _set_id)


class TestEncoder(JSONEncoder):
    def default(self, o):
        return o.__dict__

obj = Test(3)
print(TestEncoder().encode(obj))

Solution

  • Be explicit.

    def default(self, o):
        return {'id': self.__id}