Published on June 22, 2023
Go homeSimple object mapping using the built in json module in Python
Today I learned about the object_hook
input to the json.loads
and json.load
methods. I discovered this while reading this github issue.
The example referenced in the issue makes use of the SimpleNamespace
object.
import json
import types
order = json.loads(
'{"ref": "ORD1234", "price": 1.35}',
object_hook=lambda x: types.SimpleNamespace(**x),
)
order # namespace(ref='ORD1234', price=1.35)
This is a really cool feature I wished I had discovered earlier. For those instances where reaching for something like pydantic
seems overkill, maybe something like this could be useful.
import json
import dataclasses
@dataclasses.dataclass
class Order:
ref: str
price: float
@classmethod
def from_dict(cls, data: dict[str, str | float]) -> "Order":
ref = data["ref"]
price = data["price"]
return cls(ref=ref, price=price)
order = json.loads(
'{"ref": "ORD1234", "price": 1.35}',
object_hook=Order.from_dict,
)
order # Order(ref='ORD1234', price=1.35)