如何展平嵌套JSON
尝试将嵌套的json响应从2个级别深入到1个级别 以下是我在围棋场的工作代码: 我想以以下方式结束:如何展平嵌套JSON,json,go,unmarshalling,Json,Go,Unmarshalling,尝试将嵌套的json响应从2个级别深入到1个级别 以下是我在围棋场的工作代码: 我想以以下方式结束: type Social struct { GooglePlusPlusOnes uint32 `Social:"GooglePlusOne"` TwitterTweets uint32 `json:"Twitter"` LinkedinShares uint32 `json:"LinkedIn"` PinterestPins u
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"`
FacebookLikes uint32 `json:"??some_magical_nested_address??"`
FacebookShares uint32 `json:"??some_magical_nested_address??"`
FacebookComments uint32 `json:"??some_magical_nested_address??"`
FacebookTotal uint32 `json:"??some_magical_nested_address??"`
}
…而不是包含嵌套的Facebook
类型的Social
类型(见下面的代码)
我想我需要做一个自定义的UnmarshalJSON
函数,但我不知道这些函数是如何工作的,我是新手
建议
下面是上面的代码: 您可以简单地使用Facebook结构:
type Social struct {
.....
Facebook `json:"Facebook"`
}
然后像这样访问它:
social.FacebookLikes
工作示例:如果您仅使用地图,则此功能将非常有用
// 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
}
尽管如此,我还是可以通过social.FacebookLikes访问它,最终的结果仍然是Facebook嵌套。有没有办法使最终结果平淡?也许根本不使用Facebook struct?不,你有什么理由这么做吗?你是对的。最终结果实际上是相同的。对不起,几天前刚开始学围棋,所以还是个傻瓜:)我找了很久了。谢谢你!
// 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
}