1

我试图让 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"
    }
  ]
}

如果有另一个模块可以做得更好,我也愿意。谢谢!

4

1 回答 1

0

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

于 2021-02-11T09:55:58.210 回答