Home > OS >  ioutil.ReadAll and unmarshal on nested curl response returns error due to problem in key of array st
ioutil.ReadAll and unmarshal on nested curl response returns error due to problem in key of array st

Time:09-30

To give you context, I am curling to a third party endpoint, the response is similar to this one

{
    "code": 200,
    "message": "Success",
    "data": {
        "list": [
            {
               "user": "user A",
               "status" : "normal"
            },
            {
                "user": "user B",
               "status" : "normal"
            }
        ],
        "page": 1,
        "total_pages": 5000
    }
}

My struct is similar to

type User struct {
    Code    int    `json:"code"`
    Message string `json:"message"`
    Data    struct {
        List []struct {
            User   string `json:"user"`
            Status string `json:"status"`
        } `json:"list"`
        Page       int `json:"page"`
        TotalPages int `json:"total_pages"`
    } `json:"data"`
}

Please check my codes

defer response.Body.Close()
io_response, err := ioutil.ReadAll(response.Body)

returnData := User{}
err = jsoniter.Unmarshal([]byte(io_response), &returnData)
if err != nil {
   log.Println(err)
}

The code above returns an error

decode slice: expect [ or n, but found {, error found in #10 byte of ...|:{"list":{"1"

When I do fmt.Println(string(io_response)), it was returned like this:

{ "code": 200, "message": "Success", "data": { "list": { "1": { "user": "user A", "status": "normal" }, "2": { "user": "user A", "status": "normal" } }, "page": 1, "total_pages": 2000 } }

Can you please teach me how to read the response properly or how to unmarshal this? Thank you

CodePudding user response:

you can define your struct like this:

type User struct {
    Code    int    `json:"code"`
    Message string `json:"message"`
    Data    struct {
        List map[string]struct {
            User   string `json:"user"`
            Status string `json:"status"`
        } `json:"list"`
        Page       int `json:"page"`
        TotalPages int `json:"total_pages"`
    } `json:"data"`
}
  • Related