JSON → Go Struct 변환기

JSON을 json 태그가 붙은 Go struct로 변환하고, encoding/json용 Unmarshal·Marshal 헬퍼도 함께 생성합니다.

JSON에서 json 태그가 붙은 Go struct 생성

Go에서 JSON 객체를 디코딩하려면 객체마다 struct가 필요하고, 키가 Go 필드 이름과 다르면 모든 필드에 json 태그를 달아야 합니다. 이 변환기가 그 struct를 대신 작성해 줍니다. allowed_origins 같은 snake_case 키는 AllowedOrigins 같은 exported 필드와 그에 맞는 json 태그로 바뀌고, 중첩 객체는 별도의 struct 타입이 되며, 정수는 int64, 소수는 float64가 됩니다. 표준 encoding/json 패키지 기반의 Unmarshal 함수와 Marshal 메서드도 추가되므로 서드파티 의존성이 없습니다.

사용 방법

  1. 설정 파일이나 API 응답 같은 JSON 샘플을 붙여넣습니다.
  2. 루트 struct 이름을 입력합니다. 예: ServerConfig.
  3. 코드를 .go 파일에 복사하고 package main을 사용하는 패키지 이름으로 바꾼 뒤, json.Unmarshal 또는 생성된 Unmarshal 함수로 디코딩합니다.

자주 묻는 질문

숫자가 int가 아니라 int64로 생성되는 이유는 무엇인가요?
JSON은 정수 크기에 제한이 없기 때문에 어떤 플랫폼에서든 안전한 int64를 사용합니다. 값의 범위를 알고 있다면 복사한 뒤 필드를 int로 바꿔도 됩니다.
json 태그에 omitempty를 추가하려면 어떻게 하나요?
생성기는 샘플의 키와 일치하는 기본 태그만 작성합니다. Marshal 시 값이 비어 있으면 생략해야 하는 필드에 ,omitempty를 직접 추가하세요. 디코딩은 어느 쪽이든 똑같이 동작합니다.
null이거나 누락될 수 있는 필드는 어떻게 처리되나요?
샘플에서 필드가 null이거나 배열 항목 중 일부에 없으면 *string 같은 포인터 타입으로 생성되므로, 값이 없는 경우와 빈 값을 구분할 수 있습니다.

예시: JSON to Go

입력 JSON

{
  "host": "0.0.0.0",
  "port": 8080,
  "debug": false,
  "allowed_origins": ["https://jsonkit.org"],
  "database": { "dsn": "postgres://localhost/app", "max_conns": 20 }
}

생성된 Go 코드 (ServerConfig)

// Code generated from JSON Schema using quicktype. DO NOT EDIT.
// To parse and unparse this JSON data, add this code to your project and do:
//
//    serverConfig, err := UnmarshalServerConfig(bytes)
//    bytes, err = serverConfig.Marshal()

package main

import "encoding/json"

func UnmarshalServerConfig(data []byte) (ServerConfig, error) {
	var r ServerConfig
	err := json.Unmarshal(data, &r)
	return r, err
}

func (r *ServerConfig) Marshal() ([]byte, error) {
	return json.Marshal(r)
}

type ServerConfig struct {
	Host           string   `json:"host"`
	Port           int64    `json:"port"`
	Debug          bool     `json:"debug"`
	AllowedOrigins []string `json:"allowed_origins"`
	Database       Database `json:"database"`
}

type Database struct {
	DSN      string `json:"dsn"`
	MaxConns int64  `json:"max_conns"`
}

다른 언어로 JSON 변환