You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将JSON格式转换为带对应类型的Python格式?求推荐工具或代码

JSON转Python类型结构的实现方案

这里给你几种把JSON转换成带Python类型标注结构的方法,包括自定义代码和第三方库:

一、自定义Python代码(无依赖)

直接写递归遍历函数,把JSON里的每个值替换成对应的Python类型,逻辑简单易懂:

import json
import pprint

def json_to_python_types(data):
    if isinstance(data, dict):
        return {k: json_to_python_types(v) for k, v in data.items()}
    elif isinstance(data, list):
        # 非空列表取第一个元素的类型,空列表直接返回list类型
        return [json_to_python_types(data[0])] if data else list
    else:
        return type(data)

# 测试你的示例JSON
sample_json = '''{
        "data": {
            "id": 8,
            "email": "ajent.j@mail.com",
            "first_name": "Agent",
            "last_name": "J",
            "avatar": "image.jpg"
        },
        "support": {
            "url": "https://test.com/#support-heading",
            "text": "I’m an agent, but I’m from the future!"
        }
    }'''

parsed_data = json.loads(sample_json)
result = json_to_python_types(parsed_data)
pprint.pprint(result, indent=4)

运行后输出的结构和你预期的完全一致,而且不需要安装任何第三方包。

二、第三方库方案:pydantic(适合严谨的类型定义)

如果需要生成可复用的类型模型(比如TypedDict或数据类),可以用pydantic。它能帮你自动推导类型,还能做数据校验:

  1. 先安装:
pip install pydantic
  1. 动态生成模型并提取类型结构的代码:
import json
import pprint
from pydantic import create_model
from typing import Dict, Any

def create_model_from_json(data: Dict[str, Any], model_name: str = "DynamicModel"):
    fields = {}
    for k, v in data.items():
        if isinstance(v, dict):
            # 嵌套字典递归生成模型
            nested_model = create_model_from_json(v, f"{model_name}_{k.capitalize()}")
            fields[k] = (nested_model, ...)
        elif isinstance(v, list):
            elem_type = type(v[0]) if v else list
            fields[k] = (list[elem_type], ...)
        else:
            fields[k] = (type(v), ...)
    return create_model(model_name, **fields)

def model_to_type_dict(model_instance) -> Dict[str, Any]:
    type_dict = {}
    for field_name, field in model_instance.model_fields.items():
        field_type = field.annotation
        # 判断是否是嵌套模型
        if hasattr(field_type, "model_fields"):
            type_dict[field_name] = model_to_type_dict(field_type())
        else:
            type_dict[field_name] = field_type
    return type_dict

# 测试示例
sample_json = '''{
        "data": {
            "id": 8,
            "email": "ajent.j@mail.com",
            "first_name": "Agent",
            "last_name": "J",
            "avatar": "image.jpg"
        },
        "support": {
            "url": "https://test.com/#support-heading",
            "text": "I’m an agent, but I’m from the future!"
        }
    }'''

parsed_data = json.loads(sample_json)
dynamic_model = create_model_from_json(parsed_data)
model_instance = dynamic_model(**parsed_data)
result = model_to_type_dict(model_instance)
pprint.pprint(result, indent=4)

这个方案生成的类型结构更规范,适合需要后续基于类型做开发的场景。

内容的提问来源于stack exchange,提问作者lovushka

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 06:35:27