구조체 간 데이터 복사
다른 구조체에서 데이터를 복사할 때 사용하는 패턴입니다.
source := SourceStruct{...}
jsonData, _ := json.Marshal(source)
var target TargetStruct
_ = json.Unmarshal(jsonData, &target)
문자열 조합 최적화
반복문을 사용한 효율적인 문자열 결합 방법입니다.
var result string
for _, val := range input.Values {
result += strconv.Itoa(val) + ","
}
result = strings.TrimSuffix(result, ",")
JSON 직렬화/역직렬화 기본 예제
type User struct {
FullName string `json:"full_name"`
Age int `json:"age"`
Courses []string `json:"courses"`
}
func main() {
user := &User{"Jung", 30, []string{"Go", "Python"}}
jsonData, _ := json.Marshal(user)
var user2 User
_ = json.Unmarshal(jsonData, &user2)
}
Redis 해시 데이터 구조체 변환
func convertRedisToStruct() {
client := redis.NewClient(&redis.Options{Addr: "localhost:6379"})
hashData, _ := client.HGetAll("bike:123").Result()
jsonData, _ := json.Marshal(hashData)
var bike BikeStruct
_ = json.Unmarshal(jsonData, &bike)
}
구조체를 인터페이스로 변환
userData, _ := json.Marshal(&userList)
var interfaceData []interface{}
_ = json.Unmarshal(userData, &interfaceData)
JSON 문자열을 구조체로 변환
type Product struct {
ID int `json:"product_id"`
Name string `json:"product_name"`
Price float64 `json:"price"`
}
func parseProduct() {
jsonStr := `{"product_id":101,"product_name":"Laptop","price":1299.99}`
var product Product
json.Unmarshal([]byte(jsonStr), &product)
}
구조체를 JSON으로 생성
type Tech struct {
Company string `json:"-"`
Skills []string `json:"skills"`
Active bool `json:",string"`
}
func generateJSON() {
tech := Tech{"TechCo", []string{"Go", "React", "Docker"}, true}
jsonData, _ := json.MarshalIndent(tech, "", " ")
}
맵을 JSON으로 변환
func mapToJSON() {
data := map[string]interface{}{
"company": "TechCorp",
"skills": []string{"Python", "Java", "AWS"},
"active": true,
}
jsonData, _ := json.MarshalIndent(data, "", " ")
}
JSON을 구조체로 파싱
type ProductInfo struct {
ID int `json:"id"`
Name string `json:"name"`
Quantity int `json:"quantity"`
}
func parseToStruct() {
jsonData := `{"id":1001, "name":"Smartphone", "quantity":5}`
var product ProductInfo
json.Unmarshal([]byte(jsonData), &product)
}
JSON을 맵으로 파싱
func jsonToMap() {
jsonData := `{"id":1001, "name":"Smartphone", "price":999.99}`
var data map[string]interface{}
json.Unmarshal([]byte(jsonData), &data)
for key, value := range data {
switch v := value.(type) {
case string:
fmt.Printf("%s: %s\n", key, v)
case float64:
fmt.Printf("%s: %.2f\n", key, v)
}
}
}
jsoniter 라이브러리 성능 개선
표준 라이브러리 대비 2-4배 빠른 처리 속도를 제공합니다.
import jsoniter "github.com/json-iterator/go"
// 사용 예시
var result interface{}
jsoniter.Unmarshal([]byte(jsonData), &result)
gjson을 통한 JSON 데이터 접근
복잡한 경로 탐색이 가능한 고성능 라이브러리입니다.
import "github.com/tidwall/gjson"
func accessJSON() {
jsonData := `{"user":"Jung", "details":{"age":30, "location":"Seoul"}}`
// 단일 값 접근
name := gjson.Get(jsonData, "user").String()
// 중첩 값 접근
age := gjson.Get(jsonData, "details.age").Int()
// 조건 필터링
filtered := gjson.Get(jsonData, "details.#(age>25)#")
}
gjson의 고급 기능
수식과 조건을 사용한 복잡한 쿼리 처리가 가능합니다.
// 조건 필터링
result := gjson.Get(jsonData, "items.#(price>1000).name")
// 배열 변환
result := gjson.Get(jsonData, "items|@reverse")
// JSON 검증
if !gjson.Valid(jsonData) {
fmt.Println("Invalid JSON")
}