不使用struct时访问JSON属性

tom*_*456 0 go

我有一些JSON,我需要能够访问属性.由于JSON属性可能会有所不同,因此无法创建struct要解组的内容.

JSON可能是这样的:

{"name" : "John Doe", "email" : "john@doe.com"}
Run Code Online (Sandbox Code Playgroud)

或这个:

{"town" : "Somewhere", "email" : "john@doe.com"}
Run Code Online (Sandbox Code Playgroud)

或其他任何东西.

我如何访问每个属性?

rua*_*akh 5

你可以把它解组成一个interface{}.如果这样做,json.Unmarshal将将JSON对象解组为Go映射.

例如:

var untypedResult interface{}
err := json.Unmarshal(..., &untypedResult)

result := untypedResult.(map[string]interface{})

// ... now you can iterate over the keys and values of result ...
Run Code Online (Sandbox Code Playgroud)

见< http://blog.golang.org/json-and-go#TOC_5.>作为一个完整的例子.

  • 你也不需要单独的强制转换,你只需要`var result map [string] interface {}`并在`Unmarshal`中使用它.这是一个例子:http://play.golang.org/p/QeL8lIinQf (2认同)