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 關注
- 181 瀏覽
添加回答
舉報