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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
wuz
  • 483
  • 3
  • 16

1 Answers1

1

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')
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Thanks a lot. This enables me to steer the JSON result creation. One slight remark: I call the properties in __getstate__(self), for instance return {'url' self.url} because the properties encapsulate the logic to provide the appropriate value. Any design consideration with that? – wuz Nov 27 '18 at 20:07
  • @wuz: that's fine, just take into account that that is the value you'll get back to `__setstate__`. – Martijn Pieters Nov 27 '18 at 22:52
  • Thanks again for your help. Do you also know how to serialize a date property. Unfortunately, modifiy __getstate__ as fllows with strptime does not result in a json date mapping:- 'upload_date': datetime.datetime.strptime(self.upload_date, "%Y%m%d"), – wuz Dec 11 '18 at 23:04
  • @wuz: what is a JSON date mapping? JSON has no concept of dates. Does [jsonpickle datetime to readable json format](//stackoverflow.com/q/19414672) help? – Martijn Pieters Dec 13 '18 at 11:46
  • thanks for the hint. In order to make the serialized json to enable elasticsearch automated date mapping, the date has to match an exact format (e.g. yyyy-mm-dd without hh-mm-ss), all solved. – wuz Dec 14 '18 at 22:55