golang json 解组 map[string]interface{} 的一部分
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23249436/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
golang json unmarshal part of map[string]interface{}
提问by user10479
I have the following code to try to Unmarshal this json file, however the line json.Unmarshal([]byte(msg["restaurant"]), &restaurant) always gives an error. How can I make Unmarshal ignore the "restaurant" or pass only the "restaurant" data to the Unmarshal function?
我有以下代码尝试解组这个 json 文件,但是 json.Unmarshal([]byte(msg["restaurant"]), &restaurant) 行总是给出错误。如何让 Unmarshal 忽略“餐厅”或仅将“餐厅”数据传递给 Unmarshal 函数?
Thanks!
谢谢!
{
"restaurant": {
"name": "Tickets",
"owner": {
"name": "Ferran"
}
}
}
file, e := ioutil.ReadFile("./rest_read.json")
if e != nil {
fmt.Println("file error")
os.Exit(1)
}
var data interface{}
json.Unmarshal(file, &data)
msg := data.(map[string]interface{})
log.Println(msg)
log.Println(msg["restaurant"])
log.Println(reflect.TypeOf(msg["restaurant"]))
var restaurant Restaurant
json.Unmarshal([]byte(msg["restaurant"]), &restaurant)
log.Println("RName: ", restaurant.Name)
log.Println("Name: ", restaurant.Owner.Name)
采纳答案by Sebastian
I would propose to construct a proper model for your data. This will enable you to cleanly unmarshal your data into a Go struct.
我建议为您的数据构建一个合适的模型。这将使您能够将数据干净地解组为 Go 结构体。
package main
import (
"encoding/json"
"fmt"
)
type Restaurant struct {
Restaurant RestaurantData `json:"restaurant"`
}
type RestaurantData struct {
Name string `json:"name"`
Owner Owner `json:"owner"`
}
type Owner struct {
Name string `json:"name"`
}
func main() {
data := `{"restaurant":{"name":"Tickets","owner":{"name":"Ferran"}}}`
r := Restaurant{}
json.Unmarshal([]byte(data), &r)
fmt.Printf("%+v", r)
}
回答by eric gilbertson
It is possible to do generic unmarshalling ala gson by decoding into an interface and then extracting a top level map from the result, e.g:
可以通过解码为接口然后从结果中提取顶级映射来进行通用解组 ala gson,例如:
var msgMapTemplate interface{}
err := json.Unmarshal([]byte(t.ResponseBody), &msgMapTemplate)
t.AssertEqual(err, nil)
msgMap := msgMapTemplate.(map[string]interface{})
See "decoding arbitrary data" in http://blog.golang.org/json-and-gofor more into.
有关更多信息,请参阅http://blog.golang.org/json-and-go 中的“解码任意数据” 。
回答by Evan
Unmarshalling occurs recursively, so msg["restaurant"]is no longer a json string - it is another map[string]interface{}. If you want to unmarshall directly into a Restaurantobject, you will have to provide a simple wrapper object with a Restaurantmember and unmarshall into that.
解组以递归方式发生,因此msg["restaurant"]不再是 json 字符串 - 它是另一个map[string]interface{}. 如果你想直接解组到一个Restaurant对象中,你必须提供一个带有Restaurant成员的简单包装对象,然后解组到那个对象中。

