将请求中的json转换为golang中的数组

将请求中的json转换为golang中的数组,go,Go,如何将json数组转换为结构数组?例如: [ {"name": "Rob"}, {"name": "John"} ] 我正在从请求中检索json: body, err := ioutil.ReadAll(r.Body) 如何将其解组到数组中?您只需使用json.unmarshal即可。例如: import "encoding/json" // This is the type we define for deserialization. // You can use map[st

如何将json数组转换为结构数组?例如:

[
  {"name": "Rob"},
  {"name": "John"}
]
我正在从请求中检索json:

body, err := ioutil.ReadAll(r.Body)

如何将其解组到数组中?

您只需使用
json.unmarshal
即可。例如:

import "encoding/json"


// This is the type we define for deserialization.
// You can use map[string]string as well
type User struct {

    // The `json` struct tag maps between the json name
    // and actual name of the field
    Name string `json:"name"`
}

// This functions accepts a byte array containing a JSON
func parseUsers(jsonBuffer []byte) ([]User, error) {

    // We create an empty array
    users := []User{}

    // Unmarshal the json into it. this will use the struct tag
    err := json.Unmarshal(jsonBuffer, &users)
    if err != nil {
        return nil, err
    }

    // the array is now filled with users
    return users, nil

}

如果你的结构开始变得复杂或冗长,这个工具可以节省几分钟的打字时间:@Matt:Oh-wow!非常感谢您提供的工具,对于像我这样的Go n00b来说,这绝对是必须的!