英文:
Decoding JSON in Go without all key names
问题
我是你的中文翻译助手,以下是翻译好的内容:
我是Go的新手,正在尝试通过将结构体传递给Unmarshal来解码一个JSON数据块。问题是,我不知道某些键的名称。我可以解析以下JSON数据:
{"age":21,"Travel":{"fast":"yes","sick":false}}
使用以下结构体:
type user struct {
Age int
Travel TravelType
}
type TravelType struct {
Fast string
Sick bool
}
通过以下方式进行解析:
func main() {
src_json := []byte(`{"age":21,"travel":{"fast":"yes","sick":false}}`)
u := user{}
err := json.Unmarshal(src_json, &u)
if err != nil {
panic(err)
}
fmt.Printf("%v", u)
}
可以得到{21 {yes false}}
的结果。
然而,我不知道如何处理类似以下的情况:
{
"age":21,
"Travel":
{
"canada":
{"fast":"yes","sick":false},
"bermuda":
{"fast":"yes","sick":false},
"another unknown key name":
{"fast":"yes","sick":false}
}
}
而不需要在结构体中显式声明"Canada"、"Bermuda"等键名。我找到了这个答案,但不知道如何实现。
英文:
I'm new to Go and am trying to decode a json blob via feeding structs to Unmarshal. Trouble is, I dont know certain keys. I can parse the following
{"age":21,"Travel":{"fast":"yes","sick":false} }
like so
type user struct {
Age int
Travel TravelType
}
type TravelType struct {
Fast string
Sick bool
}
func main() {
src_json := []byte(`{"age":21,"travel":{"fast":"yes","sick":false}}`)
u := user{}
err := json.Unmarshal(src_json, &u)
if err != nil {
panic(err)
}
fmt.Printf("%v", u)
}
to obtain {21 {yes false}}
However, I dont see how I would approach something like this-
{
"age":21,
"Travel":
{
"canada":
{"fast":"yes","sick":false},
"bermuda":
{"fast":"yes","sick":false},
"another unknown key name":
{"fast":"yes","sick":false},
}
}
without explictly declaring "Canada", "Bermuda", etc in structs. How could I use Unmarshal to parse the above json? I found this answer, but dont see how it might be implemented
答案1
得分: 9
你可以将其解组为map[string]TravelType
。将你的user
结构体更改为以下内容,然后应该可以正常运行:
type user struct {
Age int
Travel map[string]TravelType
}
这是一个在Go Playground上的可行概念验证:http://play.golang.org/p/-4k9GE5ZlS
英文:
You can Unmarshal into a map[string]TravelType
. Change your user
struct to this and you should be good to go:
type user struct {
Age int
Travel map[string]TravelType
}
Here's a working proof-of-concept on the Go Playground: http://play.golang.org/p/-4k9GE5ZlS
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论