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 🙏

© 2026 – Pkg Stats / Ryan Hefner

aist-python-pydantic-json-schema-form

v1.0.1

Published

Dynamic React form generator from Python Pydantic model_json_schema() output

Downloads

97

Readme

aist-python-pydantic-json-schema-form

Python Pydantic model_json_schema() 출력을 기반으로 동적 React 폼을 생성하는 라이브러리

설치

# 로컬 패키지 링크
cd /Users/mskim07-macbook/Workspace/aist/aist-python-pydantic-json-schema-form
npm install
npm run build
npm link

# AI Studio Front에서 사용
cd /Users/mskim07-macbook/Workspace/aist/api-studio-front
npm link aist-python-pydantic-json-schema-form

기본 사용법

import { JsonSchemaForm } from 'aist-python-pydantic-json-schema-form';

// Pydantic model_json_schema() 결과
const schema = {
  type: 'object',
  title: 'User',
  properties: {
    name: { type: 'string', title: 'Name' },
    email: { type: 'string', format: 'email', title: 'Email' },
    age: { type: 'integer', title: 'Age', minimum: 0 },
  },
  required: ['name', 'email'],
};

function MyForm() {
  const handleSubmit = (data) => {
    console.log('Form data:', data);
  };

  return (
    <JsonSchemaForm
      schema={schema}
      onSubmit={handleSubmit}
      onChange={(data) => console.log('Changed:', data)}
    />
  );
}

Props

| Prop | Type | Default | Description | |------|------|---------|-------------| | schema | PydanticJsonSchema | required | Pydantic model_json_schema() 결과 | | onSubmit | (data: FormValues) => void | - | 제출 핸들러 | | onChange | (data: FormValues) => void | - | 실시간 변경 핸들러 | | defaultValues | FormValues | - | 초기값 | | disabled | boolean | false | 전체 비활성화 | | readOnly | boolean | false | 읽기 전용 | | showSubmitButton | boolean | true | 제출 버튼 표시 | | submitButtonText | string | 'Submit' | 버튼 텍스트 | | className | string | - | 폼 컨테이너 클래스 | | classNames | ClassNames | - | 개별 요소 클래스 커스터마이징 |

지원 JSON Schema 기능

| 기능 | Pydantic 예시 | 지원 | |------|--------------|------| | 기본 타입 | str, int, float, bool | ✅ | | Optional | Optional[str]anyOf: [{type: string}, {type: null}] | ✅ | | Enum | Literal["A", "B"]enum: ["A", "B"] | ✅ | | 중첩 모델 | Address$ref: "#/$defs/Address" | ✅ | | 배열 | List[str]type: array, items: {type: string} | ✅ | | 객체 배열 | List[Item]items: {$ref: "#/$defs/Item"} | ✅ | | Discriminated Union | Union[TypeA, TypeB] with discriminator | ✅ | | 기본값 | Field(default="value") | ✅ | | 설명 | Field(description="...") | ✅ | | 검증 | minLength, maximum, pattern | ✅ | | 포맷 | email, date, date-time, uuid, uri | ✅ |

스타일링

Tailwind CSS 클래스를 사용합니다. classNames prop으로 커스터마이징 가능합니다:

<JsonSchemaForm
  schema={schema}
  onSubmit={handleSubmit}
  classNames={{
    form: 'max-w-lg mx-auto',
    input: 'border-gray-400',
    label: 'text-gray-800 font-semibold',
    submitButton: 'bg-green-600 hover:bg-green-700',
    error: 'text-red-700',
    arrayContainer: 'bg-gray-100 p-4 rounded',
    objectContainer: 'border-l-4 border-blue-500 pl-4',
  }}
/>

고급 사용

Custom Hook 사용

import { useJsonSchemaForm, FormContext, FormField } from 'aist-python-pydantic-json-schema-form';

function CustomForm({ schema }) {
  const { contextValue, handleSubmit, values } = useJsonSchemaForm({
    schema,
    onChange: (data) => console.log(data),
  });

  return (
    <FormContext.Provider value={contextValue}>
      <form onSubmit={(e) => { e.preventDefault(); handleSubmit(); }}>
        {/* 커스텀 레이아웃 */}
        <div className="grid grid-cols-2 gap-4">
          <FormField name="firstName" path="firstName" schema={schema.properties.firstName} />
          <FormField name="lastName" path="lastName" schema={schema.properties.lastName} />
        </div>
        <button type="submit">Submit</button>
      </form>
    </FormContext.Provider>
  );
}

유틸리티 함수

import {
  resolveRef,
  generateDefaultValue,
  validateForm,
  parsePath,
  setValueAtPath,
} from 'aist-python-pydantic-json-schema-form';

// $ref 해석
const resolvedSchema = resolveRef('#/$defs/Address', rootSchema);

// 기본값 생성
const defaultValue = generateDefaultValue(schema, rootSchema);

// 폼 검증
const errors = validateForm(values, schema);

// 경로 기반 값 설정
const newValues = setValueAtPath(values, 'address.city', 'Seoul');

예제: Pydantic 모델

from pydantic import BaseModel, Field
from typing import Optional, List, Literal
from datetime import date

class Address(BaseModel):
    street: str
    city: str
    country: str = "Korea"

class User(BaseModel):
    name: str = Field(description="사용자 이름")
    email: str = Field(format="email")
    age: Optional[int] = Field(default=None, ge=0)
    role: Literal["admin", "user", "guest"] = "user"
    address: Address
    tags: List[str] = []
    birth_date: Optional[date] = None

# JSON Schema 생성
schema = User.model_json_schema()

위 Pydantic 모델의 model_json_schema() 출력으로 자동으로 폼이 생성됩니다.

개발

# 의존성 설치
npm install

# 개발 모드
npm run dev

# 빌드
npm run build

# 린트
npm run lint

License

MIT