How should/can I convert loaded JSON data into Python objects?

I have JSON input like this:

{
  "accountID": "001-002-003-004",
  "accountClass": "Primary",
  "id": "1-2",
  "openTime": "2019-12-21T02:12:17.122Z",
  "priceDifference": "0.12345",
}

I would like to deserialise it into a Python object in a way similar to how serde from Rust works.

I would like to define a class like this:

@dataclass
class MyClass:
    accountID: str
    accountClass: str
    id: str
    openTime: str
    priceDifference: float

After loading the JSON data what is the best way to serialise it into that classes object?
I know I can use kwargs for that like this:

MyClass(**json_data)

But one of the pains here is that the names would have to match therefore I cannot have snake case for names of the fields in my class (or maybe there is a way to rename those, but I dont know how).
Is there a better way to do that? Also is there a way in which I could keep the snake case naming for my class without changing the names of the JSON fields?

1 Like

Pydantic can help here

They have a section that provides a solution for your expect example

5 Likes

If you do not want to use an external package for that, here are solutions which you can extend with field name translation:

While pydantic and similar dedicated schema libraries are probably the cleanest solutions to the problem, I’d like to throw in a recommendation for python-box · PyPI as well. It is wonderful to use when exploring a new data structure.

there is msgspec / cattrs / GitHub - ltworf/typedload: Python library to load dynamically typed data into statically typed data structures

use pydantic only if you need heavy validation.

1 Like