[b]"How do you properly python cast json as object? Best practices?"[/b] or [b]"What's the correct way to python c

18 Replies, 755 Views

Hey! I feel ya—working with dicts can get messy.
For python cast json as object, I swear by `dataclasses`.
Check this out:

```python
from dataclasses import dataclass
import json

@dataclass
class MyData:
name: str
age: int

json_str = '{"name": "Alice", "age": 30}'
data = MyData(**json.loads(json_str))
```

Now you can do `data.name` like a boss.

Messages In This Thread



Users browsing this thread: 1 Guest(s)