使用 Go 解析 JSON 文件时出现问题
时间:2024-04-16
浏览:205
作者:佚名
学习知识要善于思考,思考,再思考!今天golang学习网小编就给大家带来《使用 Go 解析 JSON 文件时出现问题》,以下内容主要包含等知识点,如果你正在学习或准备学习Golang,就都不要错过本文啦~让我们一起来看看吧,能帮助到你就更好了!
问题内容
我发出 get 请求,并收到一个无法解析的 json 文件。
这是我必须解析的数据
{
"codeconv": "acc00000321",
"start": "2019-07-01t00:00:00z",
"end": "2019-08-21t00:00:00z",
"details": [
{
"idprm": "30000000123456",
"keys": [
{
"timestamp": "2019-07-01t00:00:00z",
"value": 0
},
{
"timestamp": "2019-07-01t00:30:00z",
"value": 0
},
...
]
},
{
"idprm": "30000000123457",
"keys": [
{
"timestamp": "2019-07-01t00:00:00z",
"value": 1
},
{
"timestamp": "2019-07-01t00:30:00z",
"value": 2
},
...
]
}
]
}
这是我的对象:
type apimain struct {
codeconv string `json:"codeconv"`
start string `json:"start"`
end []keys `json:"end"`
details []apidata `json:"details"`
}
//apidata match the data we receive from api
type apidata struct {
prm string `json:"idprm"`
keys []keys `json:"keys"`
}
type keys struct {
timestamp string `json:"timestamp"`
value string `json:"value"`
}
这是使用基本身份验证获取数据的方法:
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client := &http.Client{Transport: tr}
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
if login != "" && password != "" {
req.SetBasicAuth(login, password)
}
response, err := client.Do(req)
//defer response.Body.Close()
if err != nil {
return nil, err
}
if response.StatusCode != 200 {
fmt.Println(response.Body)
panic(response.Status)
}
err = json.NewDecoder(response.Body).Decode(&result)
fmt.Println("result", result) // result is empty array
如何查看问题是否出在请求中,或者问题是否出在解析中?
我得到了一个 response.body 对象,但需要对其进行解码。
解决方案
我使用以下方法修复了它:https://mholt.github.io/json-to-go/
生成了这个结构:
type AutoGenerated struct {
CodeConv string `json:"codeConv"`
Start time.Time `json:"start"`
End time.Time `json:"end"`
Details []struct {
IDPrm string `json:"idPrm"`
Keys []struct {
Timestamp time.Time `json:"timestamp"`
Value float64 `json:"value"`
} `json:"keys"`
} `json:"details"`
}
感谢您的评论
非常节省时间!
本篇关于《使用 Go 解析 JSON 文件时出现问题》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.20
11.20
11.20
11.20
热门专题
