lidatong / dataclasses-json

Easily serialize Data Classes to and from JSON
MIT License
1.34k stars 150 forks source link

Parse JSON without modifying the dataclass #515

Open mnieber opened 5 months ago

mnieber commented 5 months ago

Description

I'm always frustrated when a solution could use a function, but instead relies on creating or modifying classes.

Possible solution

Allow a functional approach to parsing a json, e.g.

@dataclass
class Person:
    name: str

person = parse(
    data=person_json, 
    cls=Person,
    encoders=dict(
        name=encode_name
    ),
    validators=dict(
        name=validate_name
    )
)

An additional benefit is that I can flexibly choose the encoders and validators (they are not baked into my Person data-structure)

person = parse(
    data=person_json_in_format_a, 
    cls=Person,
    encoders=format_a_encoders,
    validators=format_a_validators
)

Alternatives

I've looked into various solutions based on Pydantic. I haven't found any nice ones (dataclasses-json looks like it might be the nicest one so far).

Context

No response

USSX-Hares commented 4 months ago

Duplicate of https://github.com/lidatong/dataclasses-json/issues/442