arrays - go - 如何在go lang中访问json数组中的键和值
问题描述
我有一个样本如下,
result = [{"Key":"9802", "Record":{"action":"Warning","status":"Created","statusid":"9802","system":"CRM","thresholdtime":"9"}}]
我如何访问 go lang 中的阈值时间值?
我试图这样显示:result[0]["Record"]["thresholdtime"]
error: invalid operation: result[0]["Record"] (type byte does not support indexing)
谢谢
解决方案
json.Unmarshal (...) 示例应该可以帮助您入门。
这是一种方法(Go Playground):
func main() {
var krs []KeyRecord
err := json.Unmarshal([]byte(jsonstr), &krs)
if err != nil {
panic(err)
}
fmt.Println(krs[0].Record.ThresholdTime)
// 9
}
type KeyRecord struct {
Key int `json:"Key,string"`
Record Record `json:"Record"`
}
type Record struct {
Action string `json:"action"`
Status string `json:"status"`
StatusId int `json:"statusid,string"`
System string `json:"system"`
ThresholdTime int `json:"thresholdtime,string"`
}
var jsonstr = `
[
{
"Key": "9802",
"Record": {
"action": "Warning",
"status": "Created",
"statusid": "9802",
"system": "CRM",
"thresholdtime": "9"
}
}
]
`
您可以将 JSON 文档解组为泛型类型;但是,由于多种原因不建议这样做,最终与类型信息的丢失有关:
xs := []map[string]interface{}{}
err := json.Unmarshal([]byte(jsonstr), &xs)
if err != nil {
panic(err)
}
ttstr := xs[0]["Record"].(map[string]interface{})["thresholdtime"].(string)
fmt.Printf("%#v\n", ttstr) // Need to convert to int separately, if desired.
// "9"
推荐阅读
- wagtail - 鹡鸰中的蛞蝓翻译问题
- python - 使用 pyinstaller 后 Python 应用程序无法运行,但没有给出任何错误
- flutter - firebase 项目所有者更改后未反映在 Flutter Web 部署上的更改
- c - 基于另一个变量对一个值执行 MPI 的所有减少的有效方法?
- python - 将 bytearray.translate() 与表一起使用
- javascript - 在 MongoDB 中检查并将文档项添加到集合的问题
- prolog - Prolog 过程 si(A) 不存在
- matrix - CLAPACK f2c vs MKL:矩阵乘法性能问题
- sql - 用于配对网络活动参与者的关系数据库架构和查询
- css - CSS 根据屏幕大小将边距缩小为零