npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

json-to-pydantic-code-generator

v1.1.0

Published

Generate Pydantic models from JSON. A TypeScript tool that analyzes JSON structures and outputs fully typed Pydantic model code.

Readme

JSON to Pydantic Code Generator

Generate Pydantic models automatically from JSON data.

Features

  • Converts JSON objects to Pydantic model classes
  • Handles nested objects and arrays
  • Supports Python type annotations
  • Customizable output via flags
  • Supports aliasing for camelCase fields
  • Option to reuse class definitions
  • Configurable indentation
  • Option to make fields optional
  • Supports avoiding reserving Python keywords as field names

Installation

npm install json-to-pydantic-code-generator

Usage

import { generatePydanticCode } from "json-to-pydantic-code-generator";

// Also available: error classes for better error handling
import { 
  InvalidIndentationError, 
  InvalidJSONString, 
  MalformedJSONError 
} from "json-to-pydantic-code-generator";

const json = {
  "user": {
    "id": 123,
    "name": "Alice",
    "isActive": true,
    "roles": [
      { "roleId": 1, "roleName": "admin" },
      { "roleId": 2, "roleName": "user" }
    ],
    "profile": {
      "email": "[email protected]",
      "address": {
        "city": "Wonderland",
        "zip": "00000"
      }
    }
  },
  "createdAt": "2025-06-20T12:00:00Z"
};

// Accepts JSON objects, arrays, or JSON strings
const code = generatePydanticCode(json, "Root", {
  indentation: 2,
  forceOptional: "OnlyRootClass",
  aliasCamelCase: true
});
console.log(code);

Output Example

from __future__ import annotations

from typing import List, Optional

from pydantic import BaseModel, Field


class Role(BaseModel):
  role_id: int = Field(..., alias='roleId')
  role_name: str = Field(..., alias='roleName')


class Address(BaseModel):
  city: str
  zip: str


class Profile(BaseModel):
  email: str
  address: Address


class User(BaseModel):
  id: int
  name: str
  is_active: bool = Field(..., alias='isActive')
  roles: List[Role]
  profile: Profile


class Root(BaseModel):
  user: Optional[User] = None
  created_at: Optional[str] = Field(None, alias='createdAt')

Flags

  • indentation (number): Number of spaces for indentation (default: 4) (NOTE: this flag has no effect if useTabs is set to true, in which case it will use a single tab character for indentation. The tab size is determined by the environment or editor settings.)
  • preferClassReuse (boolean): Reuse identical class definitions (default: false)
  • forceOptional ("None" | "OnlyRootClass" | "AllClasses"): Make fields optional in the root or all classes (default: "None")
  • aliasCamelCase (boolean): Use snake_case for field names and set original names as aliases (default: false)
  • useTabs (boolean): Use tabs instead of spaces for indentation (default: false)

Error Handling

The package exports custom error classes for better error handling:

try {
  const code = generatePydanticCode('invalid json', 'Model');
} catch (error) {
  if (error instanceof InvalidJSONString) {
    console.log('Invalid JSON string provided');
  } else if (error instanceof InvalidIndentationError) {
    console.log('Invalid indentation value');
  }
}

Output Examples for Each Flag

1. indentation

Input:

const json = {
    "user": "Mary"
    "id": 123,
}

const code = generatePydanticCode(json, "Root", { indentation: 3 });
console.log(code);

Output:

from __future__ import annotations

from pydantic import BaseModel


class Root(BaseModel):
   user: str
   id: int

2. preferClassReuse

Input:

const json = { 
  "user1": { "name": "Alice" },
  "user2": { "name": "Bob" } 
};

const code = generatePydanticCode(json, "Root", { preferClassReuse: true });
console.log(code);

Output:

from __future__ import annotations

from pydantic import BaseModel


class User1(BaseModel):
    name: str


class Root(BaseModel):
    user1: User1
    user2: User1

3. forceOptional

Input:

const json = {
  "name": "Alice",
  "address": {
    "street": "Main St",
    "zip": "12345"
  }
}

const code = generatePydanticCode(json, "Root", {
  forceOptional: "OnlyRootClass"
});
console.log(code);

Output:

from __future__ import annotations

from typing import Optional

from pydantic import BaseModel


class Address(BaseModel):
    street: str
    zip: str

class Root(BaseModel):
    name: Optional[str] = None
    address: Optional[Address] = None

Input:

const json = {
  "name": "Alice",
  "address": {
    "street": "Main St",
    "zip": "12345"
  }
}

const code = generatePydanticCode(json, "Root", {
  forceOptional: "AllClasses"
});
console.log(code);

Output:

from __future__ import annotations

from typing import Optional

from pydantic import BaseModel


class Address(BaseModel):
    street: Optional[str] = None
    zip: Optional[str] = None

class Root(BaseModel):
    name: Optional[str] = None
    address: Optional[Address] = None

4. aliasCamelCase

Input:

const json = {
  userName: "Alice",
  emailAddress: "[email protected]"
    
}

const code = generatePydanticCode(json, "Root", { aliasCamelCase: true });
console.log(code);

Output:

from __future__ import annotations

from pydantic import BaseModel, Field


class User(BaseModel):
    user_name: str = Field(..., alias='userName')
    email_address: str = Field(..., alias='emailAddress')

License

MIT