数组的一个元素作为对象

时间:2018-05-21 11:50:09

标签: json go interface

问题是如何获得"来自"元件?剩下的不是问题

我知道在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)

1 个答案:

答案 0 :(得分:0)

很简单:它是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

相关问题