robzolkos
robzolkos

Reputation: 2266

Convert json in a request to array in golang

How can I convert a json array to an array of structs? Example:

[
  {"name": "Rob"},
  {"name": "John"}
]

I'm retrieving the json from a request:

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

How would I unmarshal this into an array?

Upvotes: 2

Views: 11681

Answers (1)

Not_a_Golfer
Not_a_Golfer

Reputation: 49177

you simply use json.Unmarshal for this. Example:

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

}

Upvotes: 10

Related Questions