Hunteerq
Hunteerq

Reputation: 280

Serializing python object to Json

I am struggling with serializing class to json file.

I tried two methodes, one to create directory, second to use jsons.

authorized_user = Login('1','test', 'test2')
vars(authorized_user)
jsons.dumps(authorized_user)

They both returned me:

{'_Login__request_type': '1', '_Login__username': 'test', '_Login__password': 'test2'}

How do I get rid of Login prefix?

What is more I would like to ask if there is a way to serialize object to json with more json naming convention. Like writing python class fields in python naming convention: __username, but parser would know that it is username.

Upvotes: 2

Views: 222

Answers (1)

yona
yona

Reputation: 434

To modify the way your class is encoded into JSON format/get rid of Login prefix, you could use one of two different parameters for json.dumps():

  1. Extending JSONEncoder (recommended)

To use a custom JSONEncoder subclass (e.g. one that overrides the default() method to serialize additional types), specify it with the cls kwarg; otherwise JSONEncoder is used.

class ComplexEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, Login):
            return {"request_type": obj.request_type, "username": obj.username, "password": obj.password}

json.dumps(authorized_user, cls=ComplexEncoder)
# {"request_type": "1", "username": "test", "password": "test2"}
  1. default param

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.

def new_encoder(obj):
    if isinstance(obj, Login):
        return {"request_type": obj.request_type, "username": obj.username, "password": obj.password}

json.dumps(authorized_user, default=new_encoder)
# {"request_type": "1", "username": "test", "password": "test2"}

Reference: https://docs.python.org/3/library/json.html

Upvotes: 2

Related Questions