在Go中解码JSON时,可以不使用所有键名。

huangapple go评论93阅读模式
英文:

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

huangapple
  • 本文由 发表于 2014年2月17日 09:16:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/21819173.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定