यह converter JSON संरचना को Pydantic v2 BaseModel classes या standard-library @dataclass कोड में बदलता है। Field नाम Python स्टाइल के अनुसार snake_case में दोबारा लिखे जाते हैं, और हर nested object को अपनी class मिलती है।
इसका इस्तेमाल FastAPI request और response schemas define करते समय, requests या httpx से लाए data में type hints जोड़ते समय, या string keys से dicts खंगालने वाली ETL और scraping scripts साफ़ करते समय करें।
टाइप का नाम में top-level model का नाम डालें (उदाहरण के लिए Forecast)।स्टाइल में validation और aliases के लिए Pydantic (v2), या बिना dependency वाले model के लिए dataclass चुनें।models.py जैसे module में कॉपी करें। स्टाइल और type का नाम URL में सेव रहते हैं।{
"city": "Seoul",
"updatedAt": "2024-05-01T09:00:00+09:00",
"current": { "temp": 18.5, "humidity": 40 },
"hourly": [
{ "hour": 10, "temp": 19, "rain_mm": 0 },
{ "hour": 11, "temp": 20.5, "rain_mm": 0.4, "alert": "shower" }
]
}from __future__ import annotations
from pydantic import BaseModel, ConfigDict, Field
class Hourly(BaseModel):
hour: int
temp: float
rain_mm: float
alert: str | None = None
class Current(BaseModel):
temp: float
humidity: int
class Forecast(BaseModel):
model_config = ConfigDict(populate_by_name=True)
city: str
updated_at: str = Field(alias="updatedAt")
current: Current
hourly: list[Hourly]
updatedAt updated_at field बनता है, जो Field(alias="updatedAt") से मूल key से जुड़ा रहता है। hourly में temp integers और decimals मिलाता है इसलिए float बनता है, और सिर्फ़ दूसरे item में मौजूद alert str | None = None है। Classes child-first क्रम में निकलती हैं।
Field(alias=...) इस्तेमाल करते हैं, और model_config = ConfigDict(populate_by_name=True) उन्हें Python नाम से भी भरने देता है।TypeError: non-default argument follows default argument से बचने के लिए बिना default वाले fields = None fields से पहले रखे जाते हैं; मूल key # JSON: "updatedAt" comment के रूप में रहती है।str, int, float, bool, list[...], और मिले-जुले types की values के लिए Any।null वाले fields X | None = None बनते हैं।class, from या type जैसे Python keywords के अंत में underscore लगता है (class_)।from __future__ import annotations शामिल है, ताकि classes क्रम चाहे जो हो एक-दूसरे को reference कर सकें।Root = list[RootItem] जैसा alias बनाता है।Frontend के साथ तय किए JSON से BaseModels बनाएं और उन्हें response_model= में या endpoint parameters के रूप में इस्तेमाल करें; OpenAPI docs अपने-आप बन जाते हैं।
Calls को Forecast.model_validate(resp.json()) में लपेटें, और जब provider किसी field का type बदले, तो ValidationError ठीक वह field path बताता है जो टूटा।
data["current"]["temp"] को forecast.current.temp बनाने से editor completion मिलता है और mypy या pyright कोड जांच सकते हैं।
@dataclass nested dicts को objects में नहीं बदलता। Forecast(**data) के बाद भी current dict ही रहता है; nested conversion चाहिए तो Pydantic या dacite जैसा helper इस्तेमाल करें।updatedAt) के साथ वापस serialize करने के लिए model_dump(by_alias=True) या model_dump_json(by_alias=True) call करें।str | None syntax इस्तेमाल करता है, इसलिए Pydantic models Python 3.10 या नया मानते हैं।str के रूप में आती हैं। Pydantic में annotation को datetime में बदलना ISO 8601 values parse करने के लिए काफ़ी है।class Config, parse_obj) नहीं बनते।populate_by_name=True किसलिए है?Default रूप से alias वाला field इनपुट में सिर्फ़ अपना alias (updatedAt) स्वीकार करता है। इस setting से आप Forecast(updated_at=...) भी लिख सकते हैं, जो tests में काम आता है।
Optional[str] पसंद है।str | None और Optional[str] का मतलब एक ही है। Python 3.9 compatibility चाहिए तो typing से Optional import करें और annotations बदल दें।
समर्थित स्टाइल Pydantic v2 और dataclass हैं। अगर इनमें से कोई चाहिए तो dataclass की field सूची सीधे TypedDict या @attrs.define class में ले जाई जा सकती है।
नहीं। जब Python नाम मूल key के बराबर हो, तो कोई Field(alias=...) या ConfigDict नहीं निकलता, इसलिए आपको rain_mm: float जैसी सादी lines मिलती हैं।