/ / गोल्स को गोंगंग में ऐरन करने के अनुरोध में कन्वर्ट करें - गो

गोल्स में सरणी के अनुरोध में जेसन को कनवर्ट करें - जाओ

मैं संरचना के एक सरणी में एक json सरणी कैसे बदल सकता हूं? उदाहरण:

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

मैं अनुरोध से जसन को पुनः प्राप्त कर रहा हूं:

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

मैं इसे एक सरणी में कैसे अनमर्ष करूंगा?

उत्तर:

जवाब के लिए 5 № 1

आप बस उपयोग करते हैं 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

}