2

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.

2
  • you could rebuild the dict removing class name: {k.split("__")[1]:v for k,v in vars(authorised_user)} Commented Apr 7, 2019 at 20:41
  • 1
    The problem is almost certainly that your Login class is using double-underscore prefixes for its attributes, which invokes name mangling. This is almost never what you want to do anyway. But in order to help you further you need to show the code for that class. Commented Apr 7, 2019 at 20:46

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

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.