jsonpickle:如何正确编码和显示重复的对象而不是引用



我正试图让jsonpickle转储数据,以便显式显示重复项,而不是使用引用。我尝试使用make_refs=False进行编码,这阻止了它使用py/id引用,但仍然没有显式显示重复项。这是我遇到的一个简单的例子:

from typing import List
import jsonpickle
class Thing:
def __init__(self, name: str = None, desc: str = None):
self.name = name
self.desc = desc
class BiggerThing:
def __init__(self, name: str = None, things: List[Thing] = None):
self.name = name
self.things = things if things else []
thing1 = Thing("First", "the first thing")
thing2 = Thing("Seoond", "the second thing")
thing3 = Thing("Third", "the third thing")
main_thing = BiggerThing("The main thing", [thing1, thing2, thing3, thing1])

如果我使用jsonpickle.encode(main_thing, make_refs=False, indent=2)进行编码,得到的结果如下:

{
"py/object": "__main__.BiggerThing",
"name": "The main thing",
"things": [
{
"py/object": "__main__.Thing",
"name": "First",
"desc": "the first thing"
},
{
"py/object": "__main__.Thing",
"name": "Seoond",
"desc": "the second thing"
},
{
"py/object": "__main__.Thing",
"name": "Third",
"desc": "the third thing"
},
"<__main__.Thing object at 0x000001FFACA08408>"
]
}

我以前没有使用过jsonpickle,所以我想我错过了一些简单的东西。我如何获得它,以便jsonpickle将以这种方式编码:

{
"py/object": "__main__.BiggerThing",
"name": "The main thing",
"things": [
{
"py/object": "__main__.Thing",
"name": "First",
"desc": "the first thing"
},
{
"py/object": "__main__.Thing",
"name": "Seoond",
"desc": "the second thing"
},
{
"py/object": "__main__.Thing",
"name": "Third",
"desc": "the third thing"
},
{
"py/object": "__main__.Thing",
"name": "First",
"desc": "the first thing"
}
]
}

如果有其他模块可以做得更好,我也对此持开放态度。非常感谢。

尝试main_thing = BiggerThing("The main thing", [thing1, thing2, thing3, thing1.copy()])

相关内容

最新更新