Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support json to dictionary #59

Closed
PeterLaudel opened this issue Jan 24, 2019 · 2 comments
Closed

Support json to dictionary #59

PeterLaudel opened this issue Jan 24, 2019 · 2 comments

Comments

@PeterLaudel
Copy link

Hey i really like your dataclass json package. Currently I like to have the feature for remember a json to an dictonary and backwards. An example:

MinionId = NewType('MinionId', int)

@dataclass_json
@dataclass
class Minion:
    minion_id: MinionId
    name: str

@dataclass_json
@dataclass
class Datas:
    minions: Dict[MinionId, Minion]
    some_value: int
    some_name: int

From the json or to the json:

{
    "minions": [
        {
            "minion_id": 1,
            "name": "minion1"
        },
        {
            "minion_id": 2,
            "name": "minion2"
        }
    ],
    "some_value": int,
    "some_name": int
}

Maybe there is already an solution to fix this.

@boisei0
Copy link

boisei0 commented Feb 8, 2019

If I don't misunderstand your question, you should be able to get the "to dict" part of this question working using the asdict function from the standard library:

from dataclasses import asdict
# assuming that datas contains your instance of Datas
assert isinstance(asdict(datas), dict)

On the other hand, considering this library uses marshmallow internally, you can also use something akin to Datas.schema().dump(datas) to get a NamedTuple, as described here in the marshmallow docs. To go from already parsed json to filling the dataclass you can do the same with Datas.schema().load(datas_dict). The similar Datas.schema().loads(datas_json_string) can be used to load from a string containing the json. Hope that helps.

@Peilonrayz
Copy link
Contributor

Your data and classes aren't the same.

  • [] is a typing.List, {} is a typing.Dict.
  • int isn't a valid JSON literal and so breaks the parsing.

The library converts to and from just fine with these accounted for.

@dataclass_json
@dataclass
class Minion:
    minion_id: int
    name: str

@dataclass_json
@dataclass
class Datas:
    minions: List[Minion]
    some_value: int
    some_name: int


data = '''{
    "minions": [
        {
            "minion_id": 1,
            "name": "minion1"
        },
        {
            "minion_id": 2,
            "name": "minion2"
        }
    ],
    "some_value": 1,
    "some_name": 1
}'''

d = Datas.from_json(data)
print(d)
print(Datas.to_json(d))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants