您有一個嵌套JSON 回應,並希望將其展平為單一級別,從而消除巢狀的Facebook 類型。為此,您可以使用自訂 UnmarshalJSON 函數。不過,更簡單、更靈活的解決方案是使用扁平化函數。
<code class="go">// Flatten takes a map and returns a new one where nested maps are replaced // by dot-delimited keys. func Flatten(m map[string]interface{}) map[string]interface{} { o := make(map[string]interface{}) for k, v := range m { switch child := v.(type) { case map[string]interface{}: nm := Flatten(child) for nk, nv := range nm { o[k+"."+nk] = nv } default: o[k] = v } } return o }</code>
在你的Go 程式碼中:
<code class="go">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) } for _, s := range social { socialMap := Flatten(s) fmt.Printf("%+v\n", socialMap) }</code>
使用扁平化的社交地圖,你將得到:
map[StumbleUpon:0 Reddit:0 Facebook.commentsbox_count:4691 Facebook.click_count:0 Facebook.total_count:298686 Delicious:0 GooglePlusOne:275234 Buzz:0 LinkedIn:0 Facebook.comment_count:38955 Facebook.like_count:82902 Facebook.share_count:176829 Twitter:7346788 Diggs:0 Pinterest:40982]
此輸出顯示了扁平化的社交地圖,其中所有Facebook 字段均可透過`Facebook....
此方法提供了一種扁平化JSON 響應的通用方法,消除對嵌套類型的需要。
以上是如何在 Go 中展平巢狀 JSON?的詳細內容。更多資訊請關注PHP中文網其他相關文章!