PHpullh
학습 라이브러리/Go/encoding/json — 직렬화

GO · 파일/IO

encoding/json — 직렬화

Go의 JSON 인코딩/디코딩. 구조체 태그로 필드명을 제어합니다.

파일/IO중급jsonMarshalUnmarshalstruct-tagomitempty

핵심 설명

Go의 JSON 인코딩/디코딩. 구조체 태그로 필드명을 제어합니다.

Go code

package main

import (
	"encoding/json"
	"fmt"
)

type Address struct {
	City    string `json:"city"`
	Country string `json:"country"`
}

type User struct {
	ID        int       `json:"id"`
	Name      string    `json:"name"`
	Email     string    `json:"email,omitempty"`  // 빈 값 생략
	Password  string    `json:"-"`                // JSON 제외
	Address   Address   `json:"address"`
	Tags      []string  `json:"tags,omitempty"`
}

func main() {
	// 인코딩 (Marshal)
	user := User{
		ID:    1,
		Name:  "Alice",
		Email: "alice@test.com",
		Address: Address{"Seoul", "Korea"},
		Tags:  []string{"admin", "dev"},
	}

	data, err := json.Marshal(user)
	if err != nil { panic(err) }
	fmt.Println(string(data))

	// 들여쓰기 있는 JSON
	pretty, _ := json.MarshalIndent(user, "", "  ")
	fmt.Println(string(pretty))

	// 디코딩 (Unmarshal)
	jsonStr := `{"id":2,"name":"Bob","address":{"city":"Busan","country":"Korea"}}`
	var decoded User
	if err := json.Unmarshal([]byte(jsonStr), &decoded); err != nil {
		panic(err)
	}
	fmt.Printf("이름: %s, 도시: %s
", decoded.Name, decoded.Address.City)

	// 동적 JSON — map 사용
	var dynamic map[string]interface{}
	json.Unmarshal([]byte(jsonStr), &dynamic)
	fmt.Println("name:", dynamic["name"])

	// json.Decoder — 스트림 디코딩
	// decoder := json.NewDecoder(r)
	// decoder.Decode(&obj)
}

학습 팁

json:"-" 태그는 필드를 JSON에서 완전히 제외합니다. 비밀번호 같은 민감 정보에 사용하세요.

주의할 점

json.Unmarshal에 포인터를 전달하지 않으면(&obj 대신 obj) 데이터가 채워지지 않습니다.

자주 묻는 질문

encoding/json — 직렬화란 무엇인가요?

Go의 JSON 인코딩/디코딩. 구조체 태그로 필드명을 제어합니다.

encoding/json — 직렬화 학습 시 주의할 점은 무엇인가요?

json.Unmarshal 에 포인터를 전달하지 않으면( &obj 대신 obj ) 데이터가 채워지지 않습니다.