Golang cannot parse json solution:
The case of the first letter of golang means that the access of members has been changed Permissions in lowercase become private. Different packages cannot access the private members of other packages, resulting in json.Marshal
(which uses reflect) unable to reflect the content.
For example, if you reimplement the json.Marshal(hp)
method under the main method, the member variables in the struct can be lowercase.
Note: If the member variables in
struct
are in lowercase, they can only be accessed within the current package.
Golang HTTP request Json response parsing method
The response data is as follows:
{ "number": 3, "message": "success", "people": [{ "craft": "ISS", "name": "Chris Cassidy" }, { "craft": "ISS", "name": "Anatoly Ivanishin" }, { "craft": "ISS", "name": "Ivan Vagner" }] }
The following is an http request and parses the json data into the structure Example
package main import ( "encoding/json" "fmt" "io/ioutil" "log" "net/http" "time" ) type people struct { Number int `json:"number"` } func main() { url := "http://api.open-notify.org/astros.json" spaceClient := http.Client{ Timeout: time.Second * 2, // Maximum of 2 secs } req, err := http.NewRequest(http.MethodGet, url, nil) if err != nil { log.Fatal(err) } req.Header.Set("User-Agent", "spacecount-tutorial") res, getErr := spaceClient.Do(req) if getErr != nil { log.Fatal(getErr) } if res.Body != nil { defer res.Body.Close() } body, readErr := ioutil.ReadAll(res.Body) if readErr != nil { log.Fatal(readErr) } people1 := people{} jsonErr := json.Unmarshal(body, &people1) if jsonErr != nil { log.Fatal(jsonErr) } fmt.Println(people1.Number) }
Recommended tutorial: "go Language Tutorial"
The above is the detailed content of What should I do if golang cannot parse json?. For more information, please follow other related articles on the PHP Chinese website!