避免 jsonpickle 使用 py/id 指向另一个对象的指针

Avoid jsonpickle using py/id pointer to another object

当使用 jsonpickle 将一个对象序列化为 json 时,我注意到诸如 datetime 之类的对象只存储了一次,然后将以后的使用存储为引用值,例如 {"py/id":1}。是否可以存储实际值而不是参考值?此引用似乎是隐藏的,并且在直接与数据库交互时会造成混淆。

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

Json 是 {"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"}}

调用时可以使用make_refs参数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)

来自文档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.

新的做事方式。以上答案是旧的。

jsonpickle.encode(my_object, unpicklable=False)

尝试使用 unpicklable 属性设置为 False

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, unpicklable=False)