1

I am using jsonpickle to turn a nested python object into json. Python class:

class Cvideo:
    def __init__(self):
        self._url = None

    @property
    def url(self):
        return self._url

    @url.setter
    def url(self, value):
        self._url = value

Module for serialization:

def create_jason_request(self, vid1: Cvideo):
    vid1 = Cvideo()
    vid1.url = entry['uploader_url'] # will get a leading underscore
    vid1.notdefinedproperty = "test" # wont get a leading underscore in json

    return jsonpickle.encode(vid, unpicklable=False)

Unfortunately the created json depicts _url instead of url. How to avoid leading underscore creation in json when using pythin properties? thanks.

4

1 回答 1

1

这是完全正常的行为。您的实例状态被存储,而不是外部 API。属性不是状态的一部分,它们仍然是方法,因此是 API 的一部分。

如果您必须url存储在 JSON 结果中,则使用该__getstate__方法返回更好地反映您的状态的字典。您必须创建一个匹配__setstate__方法:

def __getstate__(self):
    return {'url': self._url}

def __setstate__(self, state):
    self._url = state.get('url')
于 2018-11-26T22:17:21.117 回答