>  기사  >  백엔드 개발  >  Go에서 사용자 정의 UnmarshalJSON 함수를 사용하여 중첩된 JSON 데이터를 단일 수준 구조로 어떻게 평면화할 수 있나요?

Go에서 사용자 정의 UnmarshalJSON 함수를 사용하여 중첩된 JSON 데이터를 단일 수준 구조로 어떻게 평면화할 수 있나요?

Susan Sarandon
Susan Sarandon원래의
2024-10-28 14:49:02288검색

How can I flatten nested JSON data into a single level structure using custom UnmarshalJSON functions in Go?

중첩된 JSON을 평면화

중첩된 JSON 데이터를 단일 수준 구조로 평면화하는 것은 데이터 처리에서 일반적인 작업입니다. Go에서 사용자 정의 UnmarshalJSON 함수를 사용하여 이를 달성하는 방법은 다음과 같습니다.

UnmarshalJSON 함수

사용자 정의 UnmarshalJSON 함수를 사용하면 Go 구조체가 JSON 데이터의 역마샬링을 처리할 수 있습니다. UnmarshalJSON 구현을 사용하여 업데이트된 Social 구조체는 다음과 같습니다.

<code class="go">type Social struct {
    GooglePlusPlusOnes  uint32 `Social:"GooglePlusOne"`
    TwitterTweets       uint32 `json:"Twitter"`
    LinkedinShares      uint32 `json:"LinkedIn"`
    PinterestPins       uint32 `json:"Pinterest"`
    StumbleuponStumbles uint32 `json:"StumbleUpon"`
    DeliciousBookmarks  uint32 `json:"Delicious"`

    // Custom unmarshalling for the Facebook fields
    FacebookLikes       uint32 `json:"-"`
    FacebookShares      uint32 `json:"-"`
    FacebookComments    uint32 `json:"-"`
    FacebookTotal       uint32 `json:"-"`
}

// UnmarshalJSON implements the Unmarshaler interface for custom JSON unmarshalling
func (s *Social) UnmarshalJSON(data []byte) error {
    type FacebookAlias Facebook
    aux := &struct {
        Facebook FacebookAlias `json:"Facebook"`
    }{}

    if err := json.Unmarshal(data, aux); err != nil {
        return err
    }

    s.FacebookLikes = aux.Facebook.FacebookLikes
    s.FacebookShares = aux.Facebook.FacebookShares
    s.FacebookComments = aux.Facebook.FacebookComments
    s.FacebookTotal = aux.Facebook.FacebookTotal
    return nil
}</code>

사용

업데이트된 Social 구조체를 사용하면 이제 JSON 문서를 비정렬화하고 평면화할 수 있습니다.

<code class="go">package main

import (
    "encoding/json"
    "fmt"
)

type Social struct {
    // ... (same as before)
}

func (s *Social) UnmarshalJSON(data []byte) error { // ... (same as before) }

func main() {
    var jsonBlob = []byte(`[
        {"StumbleUpon":0,"Reddit":0,"Facebook":{"commentsbox_count":4691,"click_count":0,"total_count":298686,"comment_count":38955,"like_count":82902,"share_count":176829},"Delicious":0,"GooglePlusOne":275234,"Buzz":0,"Twitter":7346788,"Diggs":0,"Pinterest":40982,"LinkedIn":0}
    ]`)

    var social []Social
    err := json.Unmarshal(jsonBlob, &social)
    if err != nil {
        fmt.Println("error:", err)
    }
    fmt.Printf("%+v", social)
}</code>

이 코드는 Facebook 필드가 최상위 소셜 구조체에 병합되어 원하는 평면화된 JSON 구조를 출력합니다.

위 내용은 Go에서 사용자 정의 UnmarshalJSON 함수를 사용하여 중첩된 JSON 데이터를 단일 수준 구조로 어떻게 평면화할 수 있나요?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.