Does Pydantic v2 offer a way to construct a model from JSON Schema at runtime?
Short answer:
No, Pydantic v2 does not natively support constructing models directly from JSON Schemas at runtime.
However, there are workarounds and community tools that allow you to dynamically create Pydantic models from JSON-like data structures, which can include JSON Schemas — but with manual mapping and type construction.
🧩 Why Not Natively?
Pydantic focuses primarily on:
Forward structuring: define a model → generate a JSON schema (via .model_json_schema()).
It does not currently (as of v2.6) provide the reverse: JSON schema → Pydantic model.
💡 There's an open feature request and ongoing discussion for JSON Schema → Model conversion, but it's not implemented yet.
✅ Workaround Solutions
🔧 1. Use create_model() for runtime model creation
You can write your own parser for a subset of JSON Schema and use pydantic.create_model() to define a model dynamically.
You could integrate this into your code with a subprocess, or parse the model as a string and exec() it at runtime (less clean).
⚠️ Important Considerations
JSON Schema is expressive enough to describe types that aren't directly mappable to Pydantic models (e.g., complex combinators, dependencies, unevaluatedProperties).
Safely handling and validating arbitrary JSON schemas requires writing or using a comprehensive parser.
🔚 Summary
Feature
Supported in Pydantic v2?
Notes
model_json_schema()
✅ Yes
model → JSON Schema
Construct from JSON Schema
❌ No (not natively)
Workarounds available
Use create_model()
🔧 Yes (manual mapping)
You write your JSON Schema adapter
Third-party tools
✅ Yes
e.g., datamodel-code-generator
If you tell me what kind of JSON schemas you're dealing with, I can help you write a robust converter 😄