The code below works fine by displaying the json array data. Here is the working Json response in the code below
{"provision":"provision section 1",
"subsets": [{"item":"milk"},{"payments": [{"price": "200 usd"}]}]}
Now I have New json response as follow. In the new json response below the parameter subsets is now surrounded by brackets {}
{
"provision":{"subsets": [{"item":"milk"},{"payments": [{"price": "200 usd"}]}]}
}
If I integrate the New json in the code it shows error cannot unmarshal object into Go struct field Head.Provision. Any solutions on resolving the object issue will be appreciated
Here is the code
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
)
type Head struct {
Provision string `json:"provision"`
Subsets []Subset `json:"subsets"`
}
type Subset struct {
Payments []Payment `json:"payments"`
Item string `json:"item"`
}
type Payment struct {
Price string `json:"price"`
}
func main() {
/*
// old working json
m := []byte(`
{"provision":"provision section 1",
"subsets": [{"item":"milk"},{"payments": [{"price": "200 usd"}]}]}
`)
*/
// New json response not working
m := []byte(`
{
"provision":{"subsets": [{"item":"milk"},{"payments": [{"price": "200 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.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)
}
}
}