【问题标题】:One of the elements of the array as an object数组的元素之一作为对象
【发布时间】:2026-02-04 00:25:02
【问题描述】:

问题是如何获取“from”元素?其余的都不是问题

我知道在https://github.com/json-iterator/ 可以做到,但我不知道它是如何工作的

json:

{
  "ab": 123456789,
  "cd": [
    [
      4,
      1234,
      123456,
      1000000001,
      1234567890,
      "text",
      {
        "from": "123456"
      }
    ],
    [
      4,
      4321,
      654321,
      1000000001,
      9876543210,
      "text",
      {
        "from": "654321"
      }
    ]
  ]
}

Golang:

type test struct {
    Ab int             `json:"ab"`
    Cd [][]interface{} `json:"cd"`
}
var testvar test
json.Unmarshal(Data, &testvar)
testvar.Cd[0][6]["from"].(string)

错误:

invalid operation: testvar.Cd[0][6]["from"] (type interface {} does not support indexing)

【问题讨论】:

  • @Flimzy 作为?如果我有一个不同实体的数组(int/object/string)
  • 您是否要将您的json format 转换为struct 数据模型

标签: json go interface


【解决方案1】:

很简单:因此它是map[string]interface{}

m, ok := testvar.Cd[0][6].(map[string]interface{})

fmt.Println(m, ok, m["from"])

https://play.golang.org/p/XJGs_HsxMfZ

【讨论】:

    最近更新 更多