What should I do if golang cannot parse json?

coldplay.xixi
Release: 2020-06-24 12:00:58
Original
3992 people have browsed it

What should I do if golang cannot parse json?

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"
}]
}
Copy after login

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)
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!