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

前端 未结 3 1653
别跟我提以往
别跟我提以往 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:51

    I had a similar problem, but I had private fields with two underscore characters.

    class User:
        def __init__(self, id, name):
            self.id = id
            self.name = name
    
        @property
        def id(self):
            return self.__id
    
        @id.setter
        def id(self, id):
            self.__id = id
    
        @property
        def name(self):
            return self.__name
    
        @name.setter
        def name(self, name):
            self.__name = name
    

    Therefore, my json encoder is slightly different

    from json import JSONEncoder
    
    
    def beautify_key(str):
        index = str.index('__')
        if index <= 0:
            return str
    
        return str[index + 2:]
    
    
    class JsonEncoder(JSONEncoder):
    
        def default(self, o):
            return {beautify_key(k): v for k, v in vars(o).items()}
    

    Full answer is here.

提交回复
热议问题