我从 API 收到这种类型的响应:
{
"ok": true,
"response": "[
{
"Id": 163,
"Name": "Availability",
"Path": "Performance|Tier1",
"frequency": "ONE_MIN",
"Values": [
{
"startTimeInMillis": 1571314200000,
"occurrences": 1,
"current": 1,
"min": 0,
"max": 0,
"useRange": false,
"count": 1,
"sum": 1,
"value": 1,
"standardDeviation": 0
},
{
"startTimeInMillis": 1571314260000,
"occurrences": 1,
"current": 1,
"min": 0,
"max": 0,
"useRange": false,
"count": 1,
"sum": 1,
"value": 1,
"standardDeviation": 0
},
}
]
}
]
}
我想将其转换为时间序列格式。首先,我尝试取消对此结构的响应:
type App struct{
ID string `json:"metric_id"`
Name string `json:"metric_name"`
Path string `json:"metric_path"`
Frequency string `json:"frequency"`
Values []string `json:"metric_values"`
}
我正在这样做:
apprsp := App{}
fmt.Println(json.Unmarshal([]byte(ame.Response), &apprsp))
但是我在json.Unmarshal
时遇到错误. 我正在尝试做的是生成一个格式的 json:
{'time':'value','time1':'value2'}
其中time
/time1
和value
/value2
是startTimeInMillis
值和值数组的值。 我在 json 解组时做错了什么?应该怎么做才能解组上述数据?
您的App
结构甚至与您尝试取消封送的 json 文档没有密切关系。要取消封送 json 文档,您必须有一个与底层文档的结构略微匹配的 Go 结构。
type ResponseValue struct {
StartTime int64 `json:"startTimeMillis"`
// other elements of Values here, if you're interested in them
}
type Response struct {
Id int `json:"Id"`
Name string `json:"Name"`
Path string `json:"Path"`
Frequency string `json:"frequency"`
Values []ResponseValue `json:"Values"`
}
type Body struct {
Response []Response `json:"response"`
}
var data Body
json.Unmarshal([]byte(ame.Response),&data)
然后,您可以从data
中提取时间序列。
正如我上面的那个刚刚说的那样,您从 json 到结构的映射是错误的。 查找写入映射的一种简单方法是使用此工具 https://mholt.github.io/json-to-go/它使您能够将 json 映射到自动生成的结构。
这是您的响应结构
type Response struct {
ID int `json:"Id"`
Name string `json:"Name"`
Path string `json:"Path"`
Frequency string `json:"frequency"`
Values []struct {
StartTimeInMillis int64 `json:"startTimeInMillis"`
Occurrences int `json:"occurrences"`
Current int `json:"current"`
Min int `json:"min"`
Max int `json:"max"`
UseRange bool `json:"useRange"`
Count int `json:"count"`
Sum int `json:"sum"`
Value int `json:"value"`
StandardDeviation int `json:"standardDeviation"`
} `json:"Values"`
}