3

I'm trying to properly decode JSON String to an object.

I defined the following structs:

type AjaxModelsList struct {
    Id float64 `json:"Id"`
    Name string `json:"Name"`
    CarId float64 `json:"CarId"`
    EngName string `json:"EngName"`
}

type AjaxModelsData struct {
    ModelList []AjaxModelsList `json:"ModelList"`
}

type AjaxModels struct {
    Status bool `json:"status"`
    Data map[string]AjaxModelsData `json:"data"`

}

the defined object is

{
 "status": true,
 "data": {
 "ModelList": [{
   "Id": 1,
   "Name": "foo",
   "CarId": 1,
   "EngName": "bar"
  }]
 }
}

and I unmarshall using the following code:

c :=AjaxModels{}
if err := json.Unmarshal(body_byte,&c); err != nil {
    log.Fatalf("an error occured: %v",err)
}

and I get the following output:

an error occured: json: cannot unmarshal array into Go struct field AjaxModels.data of type main.AjaxModelsData

since I used []AjaxModelsList it's a slice so I shouldn't be getting this error. I probably missed something, but what ?

3
  • Let us continue this discussion in chat. Commented May 6, 2018 at 12:20
  • 1
    @Flimzy apparently the error message is using the tag or json key: play.golang.org/p/FhS6ekOdxiS Commented May 6, 2018 at 13:19
  • @mkopriva: Fascinating. And misleading. But good to know. Commented May 6, 2018 at 14:28

1 Answer 1

3

In the json the data structure is object[key]array, while in Go Data is map[key]struct.slice. Change Data to be map[key]slice instead.

E.g.

type AjaxModels struct {
    Status bool                      `json:"status"`
    Data   map[string][]AjaxModelsList `json:"data"`
}

https://play.golang.org/p/Sh_vKVL-D--

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.