首页 > 解决方案 > 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)

谢谢

标签: arraysjsongo

解决方案


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"

推荐阅读