Get the FREE Ultimate OpenClaw Setup Guide →

json-to-pydantic

Scanned
npx machina-cli add skill karim-bhalwani/agent-skills-collection/json-to-pydantic --openclaw
Files (1)
SKILL.md
3.0 KB

JSON to Pydantic Skill

This skill helps convert raw JSON data or API responses into structured, strongly-typed Python classes using Pydantic.

Instructions

  1. Analyze the Input: Look at the JSON object provided by the user.

  2. Infer Types:

    • string -> str
    • number -> int or float
    • boolean -> bool
    • array -> List[Type]
    • null -> Optional[Type]
    • Nested Objects -> Create a separate sub-class.
  3. Follow the Example: Review examples/ to see how to structure the output code. notice how nested dictionaries like preferences are extracted into their own class.

    • Input: examples/input_data.json
    • Output: examples/output_model.py

Style Guidelines

  • Use PascalCase for class names.
  • Use type hints (List, Optional) from typing module.
  • If a field can be missing or null, default it to None.

Outputs & Deliverables

  • Primary Output: Python Pydantic models with complete type annotations
  • Secondary Output: Validation rules and field defaults
  • Success Criteria: Models match JSON structure and include proper type hints
  • Quality Gate: Ready for integration into implementer's codebase

Constraints

  • NO business logic. Data models only.
  • NO implementation code beyond model definitions.
  • Must handle nested objects and optional fields correctly.

Common Pitfalls

  • Ignoring Nested Structures: Not extracting nested objects into separate classes creates monolithic models. Always decompose; create sub-classes for nested dicts.
  • Wrong Type Inference: Confusing null with missing fields. null = Optional, missing entirely = Field with default_factory. Be precise.
  • Generic Field Names: Using data, value, result instead of domain-specific names. Use the field name from JSON.
  • Skipping Validation: Not adding constraints like Field(min_length=1) or regex patterns. Add validation rules to the model.
  • Mixing Array Element Types: Not using Union types when arrays can contain multiple types. Use generics correctly.
  • Missing Aliases: Not mapping JSON camelCase to Python snake_case with Field aliases. Handle naming convention mismatches explicitly.

Integration Points

PhaseInput FromOutput ToContext
InputJSON response or API dataModel generationAnalyze JSON structure and infer types
DecompositionNested structuresSub-class extractionCreate separate Pydantic models for objects
IntegrationGenerated modelsimplementerUse in service layer for validation
ValidationModel with constraintsRuntime protectionPydantic validates all incoming data

Source

git clone https://github.com/karim-bhalwani/agent-skills-collection/blob/main/skills/json-to-pydantic/SKILL.mdView on GitHub

Overview

Converts raw JSON data or API responses into structured, strongly-typed Python classes using Pydantic. It infers types, creates sub-classes for nested objects, and ensures optional fields default to None when missing or null.

How This Skill Works

Analyze the input JSON, infer types (string→str, number→int/float, boolean→bool, array→List[Type], null→Optional[Type]), and generate Pydantic models with PascalCase class names. Nested dictionaries become separate sub-classes, and Field aliases can be used to map camelCase keys to snake_case.

When to Use It

  • Converting a JSON schema into ready-to-use Pydantic models for a Python client
  • Generating validation models from example JSON responses
  • Decomposing nested objects into individual sub-classes to keep models maintainable
  • Handling optional fields and null values with Optional and defaults
  • Preparing data models that align with API responses, including camelCase to snake_case aliases

Quick Start

  1. Step 1: Analyze the Input: Inspect the JSON object provided by the user.
  2. Step 2: Infer Types: Map string→str, number→int/float, boolean→bool, array→List[Type], null→Optional[Type], and create sub-classes for nested objects.
  3. Step 3: Follow the Example: Review examples to structure the output model with proper aliases and type hints.

Best Practices

  • Decompose nested dictionaries into separate sub-classes to avoid monolithic models
  • Infer types precisely: string→str, number→int or float, boolean→bool; arrays→List[Type] and use Optional for nulls
  • Default missing fields with default_factory when appropriate to distinguish missing vs null
  • Use Field aliases to map camelCase JSON keys to Python snake_case
  • Add validation constraints (e.g., Field(min_length=1)) where applicable; avoid generic field names

Example Use Cases

  • User profile JSON → UserModel with nested Address subclass
  • API response including 'preferences' object extracted as a Preferences subclass
  • Response with optional 'middleName' that may be null
  • List of items: orders with items having nested price and details
  • CamelCase JSON keys mapped to snake_case in models via Field aliases

Frequently Asked Questions

Add this skill to your agents
Sponsor this space

Reach thousands of developers