🛠️ToolsShed

JSON ke Go Struct

Mengkonversi data JSON ke tipe struct Go dengan tag field yang tepat.

Pertanyaan yang Sering Diajukan

Implementasi Kode

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.