跳到内容
🛠️ToolsShed

JSON转Go结构体

将JSON数据转换为Go结构体类型。

关于此工具

JSON to Go Struct 是一个开发者实用工具,可以自动将 JSON 数据转换为强类型的 Go 结构体定义。这个工具对于需要处理 JSON API、配置文件或数据交互格式的 Go 开发者至关重要,消除了手动定义结构体字段和相应 JSON 标签的繁琐过程。

只需将 JSON 数据粘贴到工具中,它会立即生成具有适当字段类型、名称和结构体标签(包括 json、omitempty 和其他常见标签)的 Go 结构体代码。生成的结构体在保持原始 JSON 结构的同时强制执行 Go 的类型安全,使得直接将 JSON 响应解析为类型化数据结构变得轻松。

当集成外部 API 或使用具有复杂或深度嵌套架构的第三方 JSON 数据时,这个工具特别有价值。它支持可选字段、数组、嵌套对象和特殊数据类型,为开发者在 API 集成过程中节省大量时间,同时降低类型不匹配导致的运行时错误风险。

常见问题

代码实现

import json

def to_pascal_case(s: str) -> str:
    return ''.join(word.capitalize() for word in s.replace('-', '_').split('_'))

def json_to_go_type(value, field_name: str, structs: dict) -> str:
    if value is None:
        return "interface{}"
    if isinstance(value, bool):
        return "bool"
    if isinstance(value, int):
        return "int64"
    if isinstance(value, float):
        return "float64"
    if isinstance(value, str):
        return "string"
    if isinstance(value, list):
        if not value:
            return "[]interface{}"
        elem_type = json_to_go_type(value[0], field_name, structs)
        return f"[]{elem_type}"
    if isinstance(value, dict):
        struct_name = to_pascal_case(field_name)
        fields = []
        for k, v in value.items():
            field_type = json_to_go_type(v, k, structs)
            go_name = to_pascal_case(k)
            fields.append(f'\t{go_name} {field_type} `json:"{k}"`')
        structs[struct_name] = "type " + struct_name + " struct {\n" + "\n".join(fields) + "\n}"
        return struct_name
    return "interface{}"

def json_to_go(json_str: str, root_name: str = "Root") -> str:
    data = json.loads(json_str)
    structs = {}
    json_to_go_type(data, root_name, structs)
    return "\n\n".join(structs.values())

sample = '{"name": "Alice", "age": 30, "address": {"city": "Tokyo", "zip": "100-0001"}}'
print(json_to_go(sample))

Comments & Feedback

Comments are powered by Giscus. Sign in with GitHub to leave a comment.