arrays - 如何从go lang中的json数组访问键和值

标签 arrays json go

我有一个示例,如下所示,

result = [{"Key":"9802", "Record":{"action":"Warning","status":"Created","statusid":"9802","system":"CRM","thresholdtime":"9"}}]

我如何在 go lang 中访问 thresholdtime 值?

我试图像这样显示:result[0]["Record"]["thresholdtime"]

error:  invalid operation: result[0]["Record"] (type byte does not support indexing)

谢谢

最佳答案

json.Unmarshal(...) Example应该让你开始。

这是一种方法 ( 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"

关于arrays - 如何从go lang中的json数组访问键和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52433236/

相关文章:

json - ORACLE - JSON 到键值对表

sql - 不能插入超过 150 行

go - 从 ApiGateway 中的 lambda Go 返回 Json

c# - 数组中抽象类的派生类

arrays - 无法将字节 slice 解码回结构

c - 在 C 中初始化数组

java - 从 JSON Schema 为非对象类型生成 POJO

c# - 以空值将Powershell内容保存为JSON

go - 不能在 strconv.ParseFloat 问题的参数中使用 (type []byte) 作为类型字符串

javascript - 在 ES6 中正确扩展数组/代理?