JSON को Python Pydantic model में बदलें!

JSON डालें और nested object समेत Python Pydantic model कोड बनाएं! Pydantic v2 BaseModel, dataclass, FastAPI समर्थित। SQLAlchemy ऊपर के टैब में।
JSON
परिणाम
 

JSON को Python Pydantic model में बदलें!

यह 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 साफ़ करते समय करें।

उपयोग कैसे करें

  1. जिस JSON का model बनाना है उसे पेस्ट करें।
  2. टाइप का नाम में top-level model का नाम डालें (उदाहरण के लिए Forecast)।
  3. स्टाइल में validation और aliases के लिए Pydantic (v2), या बिना dependency वाले model के लिए dataclass चुनें।
  4. परिणाम को models.py जैसे module में कॉपी करें। स्टाइल और type का नाम URL में सेव रहते हैं।

उदाहरण

इनपुट (JSON)
{
  "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" }
  ]
}
आउटपुट (Python · Pydantic v2)
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 क्रम में निकलती हैं।

समर्थित सुविधाएँ

  • Pydantic v2: rename हुए fields Field(alias=...) इस्तेमाल करते हैं, और model_config = ConfigDict(populate_by_name=True) उन्हें Python नाम से भी भरने देता है।
  • dataclass: TypeError: non-default argument follows default argument से बचने के लिए बिना default वाले fields = None fields से पहले रखे जाते हैं; मूल key # JSON: "updatedAt" comment के रूप में रहती है।
  • Types: str, int, float, bool, list[...], और मिले-जुले types की values के लिए Any।
  • कुछ items में न मौजूद या null वाले fields X | None = None बनते हैं।
  • class, from या type जैसे Python keywords के अंत में underscore लगता है (class_)।
  • from __future__ import annotations शामिल है, ताकि classes क्रम चाहे जो हो एक-दूसरे को reference कर सकें।
  • Top-level array Root = list[RootItem] जैसा alias बनाता है।

उपयोग के मामले

FastAPI response models और request bodies

Frontend के साथ तय किए JSON से BaseModels बनाएं और उन्हें response_model= में या endpoint parameters के रूप में इस्तेमाल करें; OpenAPI docs अपने-आप बन जाते हैं।

Third-party API responses validate करना

Calls को Forecast.model_validate(resp.json()) में लपेटें, और जब provider किसी field का type बदले, तो ValidationError ठीक वह field path बताता है जो टूटा।

Scripts में dict lookups बदलना

data["current"]["temp"] को forecast.current.temp बनाने से editor completion मिलता है और mypy या pyright कोड जांच सकते हैं।

नोट्स और सीमाएँ

  • @dataclass nested dicts को objects में नहीं बदलता। Forecast(**data) के बाद भी current dict ही रहता है; nested conversion चाहिए तो Pydantic या dacite जैसा helper इस्तेमाल करें।
  • Pydantic में मूल JSON keys (updatedAt) के साथ वापस serialize करने के लिए model_dump(by_alias=True) या model_dump_json(by_alias=True) call करें।
  • आउटपुट str | None syntax इस्तेमाल करता है, इसलिए Pydantic models Python 3.10 या नया मानते हैं।
  • Date और time strings str के रूप में आती हैं। Pydantic में annotation को datetime में बदलना ISO 8601 values parse करने के लिए काफ़ी है।
  • Pydantic v1 constructs (class Config, parse_obj) नहीं बनते।

अक्सर पूछे जाने वाले प्रश्न

populate_by_name=True किसलिए है?

Default रूप से alias वाला field इनपुट में सिर्फ़ अपना alias (updatedAt) स्वीकार करता है। इस setting से आप Forecast(updated_at=...) भी लिख सकते हैं, जो tests में काम आता है।

मुझे optional fields के लिए Optional[str] पसंद है।

str | None और Optional[str] का मतलब एक ही है। Python 3.9 compatibility चाहिए तो typing से Optional import करें और annotations बदल दें।

क्या यह TypedDict या attrs classes बना सकता है?

समर्थित स्टाइल Pydantic v2 और dataclass हैं। अगर इनमें से कोई चाहिए तो dataclass की field सूची सीधे TypedDict या @attrs.define class में ले जाई जा सकती है।

जब keys पहले से snake_case हों तो क्या aliases जुड़ते हैं?

नहीं। जब Python नाम मूल key के बराबर हो, तो कोई Field(alias=...) या ConfigDict नहीं निकलता, इसलिए आपको rain_mm: float जैसी सादी lines मिलती हैं।