🐍

JSON to Python

Generate Python dataclass or TypedDict from sample JSON with nested types, List generics and Optional fields for API response typing and config parsing.

json-to-go.input
json-to-go.output
from typing import List, Optional, Any
from dataclasses import dataclass

@dataclass
class Profile:
    age: int
    city: str

@dataclass
class RootObject:
    id: int
    name: str
    active: bool
    score: float
    tags: List[str]
    profile: Profile

关于 JSON to Python

Python 的动态类型虽灵活,但在大型项目中类型注解能大幅减少 bug。本工具在浏览器本地解析样例 JSON,自动生成 Python dataclass 或 TypedDict:字段名转为 snake_case,嵌套对象拆分为独立类,数组推断为 List[T],null 值标记为 Optional[Any]。数据不上传。

使用方法

  1. 打开 JSON to Python 工具页面
  2. 根据需求输入或粘贴数据到输入区域
  3. 查看实时处理结果,使用复制按钮获取输出

使用场景

  • 类型化 API 响应 — 把接口 JSON 转成 dataclass,配合 httpx/pydantic 做类型校验。
  • 配置文件建模 — 从 JSON/YAML 配置样例生成 dataclass,用于 typed-settings 等库。
  • FastAPI 请求体 — 快速生成 Pydantic 兼容的 dataclass 作为请求体模型。
  • 数据管道建模 — 为 ETL 管道的输入输出快速建模,提高代码可维护性。

常见问题

dataclass 和 TypedDict 有什么区别?

dataclass 是运行时可实例化的类,TypedDict 仅用于类型注解(dict 的结构化版本)。按需选择。

null 值怎么处理?

null 值推断为 Optional[Any],建议用非空样例获得更精确的类型。

字段名如何转换?

JSON 的 camelCase 或 kebab-case 字段名会自动转为 Python 风格的 snake_case。

需要哪些依赖?

dataclass 模式需要 Python 3.7+(标准库),TypedDict 需要 typing_extensions(3.8 以下)。

评论与讨论

还没有评论,来抢沙发吧!

💬 评论仅保存在你的浏览器本地,切换设备后不可见。配置 Giscus 后可支持云端评论。