[go] Go에서 JSON 데이터 중복 제거하기

이번에는 Go 언어를 사용하여 JSON 데이터에서 중복을 제거하는 방법에 대해 알아보겠습니다.

JSON 데이터 구조

가장 먼저, JSON 데이터 구조를 이해해야 합니다. JSON은 key-value 쌍으로 구성된 데이터 형식입니다. 중복된 key는 허용되지 않기 때문에, 중복된 key가 있는 데이터를 처리해야 할 때가 있습니다.

중복 제거 알고리즘

중복된 key를 제거하기 위한 간단한 알고리즘은 다음과 같습니다.

package main

import (
    "encoding/json"
    "fmt"
    "strings"
)

func main() {
    data := `{"name": "John", "age": 30, "name": "Alice"}`
    var jsonData interface{}
    err := json.Unmarshal([]byte(data), &jsonData)
    if err != nil {
        fmt.Println(err)
        return
    }
    
    cleanData, _ := removeDuplicateKeys(jsonData)
    result, _ := json.Marshal(cleanData)
    fmt.Println(string(result))
}

func removeDuplicateKeys(data interface{}) (map[string]interface{}, error) {
    cleanData := make(map[string]interface{})
    switch d := data.(type) {
    case map[string]interface{}:
        for k, v := range d {
            cleanData[k] = v
        }
    default:
        return nil, fmt.Errorf("unsupported type %T", d)
    }
    return cleanData, nil
}

위 코드에서는 removeDuplicateKeys 함수를 사용하여 JSON 데이터에서 중복을 제거합니다.

결론

Go 언어를 사용하여 JSON 데이터에서 중복된 key를 제거하는 방법에 대해 알아보았습니다. 위에서 제시한 알고리즘은 간단한 예제를 위한 것이며, 실제 환경에서는 더 복잡한 데이터 구조를 다루어야 할 수도 있습니다.

더 많은 정보는 Go 언어 공식 문서를 확인하시기 바랍니다.