在 Go 中解组动态 json 内容 [英] Unmarshal dynamic json content in Go
问题描述
我有一个动态 json 对象,我想在我的 Go 应用程序中对其进行解组.问题是json的某些部分是动态命名的,所以不知道在struc类型的json标签里放什么.为了说明我的问题,请看这个游乐场:https://play.golang.org/p/q8J0VVO7uj
I have a dynamic json object which I want to unmarshal in my Go app. The problem is that some parts of the json are dynamically named, so I don't know what to put in the struc type json tags. To illustrate my problem, please see this playground: https://play.golang.org/p/q8J0VVO7uj
如您所见,s1
可以完全解组,因为结构类型确实具有标记 description
.但是 s2
不能解组.
As you can see the s1
can perfectly be unmarshalled, because the struct type indeed has tag description
. But s2
cannot be unmarshalled.
所以我的问题是:我该如何解决这个问题?我可以使用这里的接口吗?
So my question is: how can I solve this? Can I make use of interfaces here?
推荐答案
对动态键使用映射:
type ElvisEvent struct {
Timestamp int64 `json:"timestamp"`
Type string `json:"type"`
AssetID string `json:"assetId"`
Metadata struct {
} `json:"metadata"`
ChangedMetadata map[string]struct {
OldValue interface{} `json:"oldValue"`
NewValue interface{} `json:"newValue"`
} `json:"changedMetadata"`
}
这篇关于在 Go 中解组动态 json 内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!