问题描述

所以我正在尝试解析 JSON 响应.它可以是多个级别的深度.这就是我所做的:

So I'm trying to parse a JSON response. It can be multiple levels deep. This is what I did:

var result map[string]interface{}
json.Unmarshal(apiResponse, &result)

首先,这是正确的做法吗?

假设响应如下:

{
  "args": {
            "foo": "bar"
          }
}
foo
foo
result["args"].(map[string]interface{})["foo"]
.()
.()

推荐答案

x.(T)
xTx.(T)xnilxT
xTx.(T)xnilxT

你的例子:

result["args"].(map[string]interface{})["foo"]
"args"resultsmap[string]interface{}string"foo"
results"args"map[string]interface{}string"foo"
map[string]interface{}structstruct类型,例如:

If you know noting about the input JSON format, then yes, you have to use a generic map[string]interface{} type to process it. If you know the exact structure of the input JSON, you can create a struct to match the expected fields, and doing so you can unmarshal a JSON text into a value of your custom struct type, for example:

type Point struct {
    Name string
    X, Y int
}

func main() {
    in := `{"Name":"center","X":2,"Y":3}`

    pt := Point{}
    json.Unmarshal([]byte(in), &pt)

    fmt.Printf("Result: %+v", pt)
}

输出:

Result: {Name:center X:2 Y:3}

在 Go Playground 上试试.

您当前的 JSON 输入可以使用这种类型建模:

Your current JSON input could be modelled with this type:

type Data struct {
    Args struct {
        Foo string
    }
}
d := Data{}
json.Unmarshal([]byte(in), &d)
fmt.Println("Foo:", d.Args.Foo)

这篇关于在 Golang 中访问类型 map[string]interface{} 的嵌套映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!