1

Why does the following

import json
from dataclasses import dataclass

@dataclass
class Foo(dict):
    bar: Dict

example = Foo(bar={'spam': 'eggs'})
json.dumps(example)

yield an empty dict in json string form

'{}'

Note: I'm aware that this isn't a sensible struct, rather, just interested in the reason behind the result!

Alexander McFarlane
  • 10,643
  • 9
  • 59
  • 100
  • 1
    The REASON is that the `json` module only knows how to convert integers, floats, strings, tuples, lists and dictionaries. A `dataclass` behaves a lot like a dictionary, but not enough like one. – Tim Roberts Aug 23 '23 at 03:11
  • 2
    The dict that gets serialized by `json.dumps()` is the one the the instance of `Foo` actually is, rather than one that happens to be stored in an attribute of that instance. – jasonharper Aug 23 '23 at 03:13
  • 1
    Ah yes! It's because the `dict` is actually truly empty... The attributes and extras added by `dataclass` just ignored. Indeed `dict(example)` gives `{}`... – Alexander McFarlane Aug 23 '23 at 03:15
  • A [`TypedDict`](https://peps.python.org/pep-0589/) may be more suited to your purpose. – blhsing Aug 23 '23 at 03:17
  • "Ah yes! It's because the dict is actually truly empty." - yes, exactly that. The same reason that it would fail the same way, *without* the `dataclass` decorator. – Karl Knechtel Aug 23 '23 at 03:19

1 Answers1

-1

I think you have to use the dataclasses.asdict() function to convert the dataclass to dict type obj

import json
from dataclasses import dataclass
import dataclasses

@dataclass
class Foo(dict):
    bar: dict

example = Foo(bar={'spam': 'eggs'})
print(json.dumps(dataclasses.asdict(example)))
tax evader
  • 2,082
  • 1
  • 7
  • 9
  • I'm afraid this doesn't answer the question. The question is *why* it yields `'{}'`. You answered *"how to correctly parse a dataclass into json?"* which is a duplicate of https://stackoverflow.com/questions/51286748/make-the-python-json-encoder-support-pythons-new-dataclasses – Alexander McFarlane Aug 23 '23 at 03:10