How to convert Object with Properties to JSON without “_” in Python 3?

前端 未结 3 1650
别跟我提以往
别跟我提以往 2021-01-12 12:57

I would like to convert an Python object into JSON-format.

The private attributes of the class User are defined using properties. The method to_Json()

3条回答
  •  别那么骄傲
    2021-01-12 13:40

    If the example code you posted mirrors your real code, there really isn't any reason for the properties at all. You could just do:

    class User(object):
        def __init__(self):
            self.name = None
            self.age = None
    

    since you're not really hiding anything from the user behind the underscores and properties anyway.

    If you do need to do the transformation, I like to do it in a custom encoder:

    class MyEncoder(json.JSONEncoder):
        def default(self, o):
            return {k.lstrip('_'): v for k, v in vars(o).items()}
    
    json_encoded_user = json.dumps(some_user, cls=MyEncoder)
    

提交回复
热议问题