Skip to content
πŸ› οΈToolsShed

JSON to Go Struct

Convert JSON data to Go struct types with proper field tags.

About this tool

JSON to Go Struct is a developer utility that automatically converts JSON data into strongly-typed Go struct definitions. This tool is essential for Go developers who need to work with JSON APIs, configuration files, or data interchange formats, eliminating the tedious manual process of defining struct fields and their corresponding JSON tags.

Simply paste your JSON data into the tool and it instantly generates Go struct code with proper field types, names, and struct tags (including json, omitempty, and other common tags). The generated structs preserve the original JSON structure while enforcing Go's type safety, making it easy to parse JSON responses directly into typed data structures.

This tool is particularly valuable when integrating external APIs or consuming third-party JSON data where the schema is complex or deeply nested. It supports optional fields, arrays, nested objects, and special data types, saving developers significant time during API integration and reducing the risk of runtime errors from type mismatches.

Frequently Asked Questions

Code Implementation

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.