我正在尝试让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"
}
]
}如果有另一个模块可以做得更好,我也很乐意这样做。谢谢!
发布于 2021-02-11 17:55:58
试试main_thing = BiggerThing("The main thing", [thing1, thing2, thing3, thing1.copy()])
https://stackoverflow.com/questions/61566474
复制相似问题