golang json unmarshal part of map[string]interface{}

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

golang json unmarshal part of map[string]interface{}

问题

我有以下代码尝试解析这个JSON文件,但是json.Unmarshal([]byte(msg["restaurant"]), &restaurant)这一行总是报错。我该如何让Unmarshal忽略"restaurant"或者只传递"restaurant"数据给Unmarshal函数?

谢谢!

{
  "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)
英文:

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?

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)

答案1

得分: 21

可以通过解码为接口,然后从结果中提取顶层映射来实现类似gson的通用解组,例如:

var msgMapTemplate interface{}
err := json.Unmarshal([]byte(t.ResponseBody), &msgMapTemplate)
t.AssertEqual(err, nil)
msgMap := msgMapTemplate.(map[string]interface{})

在http://blog.golang.org/json-and-go的"decoding arbitrary data"部分可以了解更多信息。

英文:

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:

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-go for more into.

答案2

得分: 12

我建议为您的数据构建一个适当的模型。这将使您能够将数据清晰地解组为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)
}

请注意,我已经将代码中的引号从"更改为正常的双引号",以使其成为有效的Go代码。

英文:

I would propose to construct a proper model for your data. This will enable you to cleanly unmarshal your data into a Go struct.

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)
}

答案3

得分: 2

解组操作是递归进行的,所以msg["restaurant"]不再是一个JSON字符串,而是另一个map[string]interface{}。如果你想直接解组成一个Restaurant对象,你需要提供一个简单的包装对象,其中包含一个Restaurant成员,并将其解组到该对象中。

英文:

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 Restaurant object, you will have to provide a simple wrapper object with a Restaurant member and unmarshall into that.

huangapple
  • 本文由 发表于 2014年4月23日 23:51:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/23249436.html
匿名

发表评论

匿名网友

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

确定