1

I'm trying to get jsonpickle to dump the data such that duplicate items are explicitly displayed rather than using references. I tried encoding with make_refs=False, which prevented it from using the py/id references but still didn't explicitly show the duplicate item. This is a simplistic example of what I'm running into:

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])

If I then encode using jsonpickle.encode(main_thing, make_refs=False, indent=2), the result I get looks like this:

{
  "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>"
  ]
}

I've not used jsonpickle before, so I'm assuming I'm missing something simple. How do I get it so that jsonpickle will encode it this way instead:

{
  "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"
    }
  ]
}

If there's another module that'll do this better, I'm open to that too. Thank you!

fny82
  • 185
  • 3
  • 13

1 Answers1

0

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