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.
This is entirely normal behaviour. Your instance state is stored, not the outside API. Properties are not part of the state, they are still methods and thus are part of the API.
If you must have url
stored in the JSON result, then use the __getstate__
method to return a dictionary that better reflects your state. You'll have to create a matching __setstate__
method:
def __getstate__(self):
return {'url': self._url}
def __setstate__(self, state):
self._url = state.get('url')