解析服务器发送的数组/切片

A server is sending back such a response:

me@linux:~> curl -X GET http://*.*.*.*:8080/profiles

[
        {
                "ProfileID": 1,
                "Title": "65micron"
        },
        {
                "ProfileID": 2,
                "Title": "80micron"
        }
]

I have tried this solution to parse the response as JSON but it only works if the server response is like this:

{
    "array": [
        {
                "ProfileID": 1,
                "Title": "65micron"
        },
        {
                "ProfileID": 2,
                "Title": "80micron"
        }
    ]
}

Does anybody know how I can parse the server response as JSON?


One idea which occurred to me is to add { "array": to the beginning of http.Response.Body buffer and also add } to the its end, then use the standard solution. However, I'm not sure if that's the best idea.

You can unmarshal directly into an array

data := `[
    {
        "ProfileID": 1,
        "Title": "65micron"
    },
    {
        "ProfileID": 2,
        "Title": "80micron"
    }]`

type Profile struct {
    ProfileID int
    Title     string
}

var profiles []Profile

json.Unmarshal([]byte(data), &profiles)

You can also read directly from the Request.Body.

func Handler(w http.ResponseWriter, r *http.Request) {

    var profiles []Profile
    json.NewDecoder(r.Body).Decode(&profiles)
    // use `profiles`
}

Playground

You should define a struct

type Profile struct {
    ID int `json:"ProfileID"`
    Title string `json:"Title"`
}

After that decode response

var r []Profile
err := json.NewDecoder(res.Body).Decode(&r)