2 回答
TA贡献1815条经验 获得超10个赞
下面是我是如何让它工作的。谢谢
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
)
type Head struct {
Provision Prov `json:"provision"`
//Subsets []Subset `json:"subsets"`
}
type Prov struct {
Subsets []Subset `json:"subsets"`
}
type Subset struct {
Payments []Payment `json:"payments"`
Item string `json:"item"`
}
type Payment struct {
Price string `json:"price"`
}
func main() {
m := []byte(`
{"provision":
{"subsets": [{"item":"milk"},{"payments": [{"price": "200 usd"}]},
{"item":"SUGAR"},{"payments": [{"price": "600 usd"}]}
]}
}
`)
r := bytes.NewReader(m)
decoder := json.NewDecoder(r)
val := &Head{}
err := decoder.Decode(val)
if err != nil {
log.Fatal(err)
}
//fmt.Println(val.Provision)
// Subsets is a slice so you must loop over it
for _, s := range val.Provision.Subsets {
fmt.Println(s.Item)
// within Subsets, payment is also a slice
// then you can access each price
for _, a := range s.Payments {
fmt.Println(a.Price)
}
}
}
TA贡献1862条经验 获得超6个赞
type Head struct {
Provision Provision `json:"provision"`
}
type Provision struct {
Subsets []Subset `json:"subsets"`
}
https://play.golang.org/p/3TgxBOng1qE完整版在这里。
- 2 回答
- 0 关注
- 148 浏览
添加回答
举报