展平巢狀 JSON
將巢狀 JSON 資料展平為單級結構是資料處理中的常見任務。以下是如何使用自訂 UnmarshalJSON 函數在 Go 中實現此目的:
UnmarshalJSON 函數
自訂 UnmarshalJSON 函數允許 Go 結構體處理 JSON 資料的解組。這是使用UnmarshalJSON 實現更新的社交結構:
<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>
用法
使用更新的社交結構,您現在可以解組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>
此程式碼將輸出您想要的扁平JSON 結構,並將Facebook 欄位合併到頂層社交結構中。
以上是如何使用 Go 中的自訂 UnmarshalJSON 函數將巢狀 JSON 資料展平為單級結構?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

Go語言的核心特性包括垃圾回收、靜態鏈接和並發支持。 1.Go語言的並發模型通過goroutine和channel實現高效並發編程。 2.接口和多態性通過實現接口方法,使得不同類型可以統一處理。 3.基本用法展示了函數定義和調用的高效性。 4.高級用法中,切片提供了動態調整大小的強大功能。 5.常見錯誤如競態條件可以通過gotest-race檢測並解決。 6.性能優化通過sync.Pool重用對象,減少垃圾回收壓力。

Go語言在構建高效且可擴展的系統中表現出色,其優勢包括:1.高性能:編譯成機器碼,運行速度快;2.並發編程:通過goroutines和channels簡化多任務處理;3.簡潔性:語法簡潔,降低學習和維護成本;4.跨平台:支持跨平台編譯,方便部署。

關於SQL查詢結果排序的疑惑學習SQL的過程中,常常會遇到一些令人困惑的問題。最近,筆者在閱讀《MICK-SQL基礎�...

golang ...

Go語言中如何對比並處理三個結構體在Go語言編程中,有時需要對比兩個結構體的差異,並將這些差異應用到第�...

GoLand中自定義結構體標籤不顯示怎麼辦?在使用GoLand進行Go語言開發時,很多開發者會遇到自定義結構體標籤在�...


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

MantisBT
Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

ZendStudio 13.5.1 Mac
強大的PHP整合開發環境

SublimeText3漢化版
中文版,非常好用

Atom編輯器mac版下載
最受歡迎的的開源編輯器