1

json.Unmarshal 将 JSON 转换为interface{}. 我无法键入断言它。http://play.golang.org/p/NAe8voYnb8

package main

import (
    "encoding/json"
    "log"
)

func main() {
    b := []byte(`{"key1":[
                          {"apple":"A", "banana":"B", "id": "C"},
                          {"cupcake": "C", "pinto":"D"}
                         ]
                  }`)

    var data interface{}
    _ = json.Unmarshal(b, &data)

    log.Println(data)
    // map[key1:[map[apple:A id:C banana:B] map[cupcake:C pinto:D]]]

    ndata, ok := data.(map[string][]map[string]string)
    log.Println(ok, ndata)
    // false map[]

    key_data, ok := ndata["key1"].([]map[string]string)
    log.Println(ok, key_data)
    // false []
}

有谁知道怎么回事?

4

2 回答 2

5

例如,

package main

import (
    "encoding/json"
    "log"
)

func somefunc(data interface{}) {
    log.Printf("%T\n", data)
    // Prints: map[string]interface {}
    log.Println(data)
    // Correctly prints: map[key1:[map[apple:A id:C banana:B] map[cupcake:C pinto:D]]]

    ndata, _ := data.(map[string]interface{})
    log.Println(ndata)
    // Should print: map[key1:[map[apple:A banana:B id:C] map[cupcake:C pinto:D]]]

    key_data, _ := ndata["key1"]
    log.Println(key_data)
    // Should print: [map[apple:A banana:B id:C] map[cupcake:C pinto:D]]]
}

func main() {
    b := []byte(`{"key1":[{"apple":"A", "banana":"B", "id": "C"},{"cupcake": "C", "pinto":"D"}]}`)
    var m interface{}
    _ = json.Unmarshal(b, &m)
    somefunc(m)
}

输出:

2012/10/18 18:21:43 map[string]interface {}
2012/10/18 18:21:43 map[key1:[map[apple:A id:C banana:B] map[cupcake:C pinto:D]]]
2012/10/18 18:21:43 map[key1:[map[banana:B apple:A id:C] map[pinto:D cupcake:C]]]
2012/10/18 18:21:43 [map[banana:B apple:A id:C] map[pinto:D cupcake:C]]
于 2012-10-18T22:09:00.590 回答
1

如果您需要一种简单的方法来处理嵌套的 JSON 数据,我已经编写了一个包来做到这一点: https ://github.com/opesun/jsonp

这减轻了必须在每个级别都键入 assert 的痛苦。有关说明,请参阅文档。

于 2012-10-19T17:11:54.370 回答