键入断言嵌套接口

问题描述 投票:0回答:3

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 []
}

有人知道怎么回事吗?

go type-assertion
3个回答
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]]

1
投票

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

这减轻了必须在每个级别键入断言的痛苦。请参阅文档了解说明。


0
投票

来自 https://pkg.go.dev/encoding/json#Unmarshal

To unmarshal JSON into an interface value, Unmarshal stores one of these in the interface value:

bool, for JSON booleans
float64, for JSON numbers
string, for JSON strings
[]interface{}, for JSON arrays
map[string]interface{}, for JSON objects
nil for JSON null

这些是您需要进行类型断言的类型。

© www.soinside.com 2019 - 2024. All rights reserved.