Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid jsonpickle using py/id pointer to another object

When an object is serialized to json using jsonpickle, I noticed objects such as datetime are stored once then future uses are stored as references value such as {"py/id":1}. Is it possible store actual value instead of reference? This reference seems hidden and would be confusing when interacting directly with database.

Ex. class MyClass: def __init__(self, eee): now = datetime.datetime.utcnow() self.ddd = now self.ddd2 = now self.ddd3 = now

Json is {"py/object": "__main__.MyClass", "py/state": {"ddd": {"py/object": "datetime.datetime", "__reduce__": [{"py/type": "datetime.datetime"}, ["B+IBFhYJCwx9oQ=="]]}, "ddd2": {"py/id": 1}, "ddd3": {"py/id": 1}, "eee": "fwaef"}}

like image 840
ferk86 Avatar asked Dec 10 '22 08:12

ferk86


2 Answers

New way of doing. Above answer is old.

jsonpickle.encode(my_object, unpicklable=False)

like image 56
pravinbhogil Avatar answered Dec 12 '22 20:12

pravinbhogil


You can use the make_refs parameter when invoking jsonpickle.encode:

import datetime
import jsonpickle

class MyClass:
    def __init__(self, eee):
        now = datetime.datetime.utcnow()
        self.ddd = now
        self.ddd2 = now
        self.ddd3 = now

my_object = MyClass('hi')
jsonpickle.encode(my_object, make_refs=False)

From the documentation here:

make_refs – If set to False jsonpickle’s referencing support is disabled. Objects that are id()-identical won’t be preserved across encode()/decode(), but the resulting JSON stream will be conceptually simpler. jsonpickle detects cyclical objects and will break the cycle by calling repr() instead of recursing when make_refs is set False.

like image 33
Adam Avatar answered Dec 12 '22 20:12

Adam