如何在 Go 语言中获取此类数据?

How can I get this type of data in Go lang?

这是API响应数据,看起来像这样。

{   
    "result":1,
    "message":"",
    "pds": [
                {
                    "state":"Y",
                    "code":13,
                    "name":"AAA",
                    "price":39900,
                },
                {
                    "state":"Y",
                    "code":12,
                    "name":"BBB",
                    "price":38000,
                }
            ],
    "request":
            {
                "op":"new",
            }
}

如何在 Go 语言中获取这些数据? 我尝试了 json.Unmarshall 并使用 map[string]interface{} 获取数据,但看起来我使用了错误的类型来获取数据。 我应该使用结构吗??

如果您不希望 json.Unmarshall 输出为 map[string]interface{}.

,则需要创建一个结构来正确处理此问题

如果将此 JSON 对象映射到 Go 结构,您会发现以下结构:

type APIResponse struct {
    Result  int    `json:"result"`
    Message string `json:"message"`
    Pds     []struct {
        State string     `json:"state"`
        Code  int        `json:"code"`
        Name  string     `json:"name"`
        Price float64    `json:"price"`
    } `json:"pds"`
    Request struct {
        Op string `json:"op"`
    } `json:"request"`
}

您还可以找到一个很棒的工具来将 JSON 对象转换为 Go 结构 here

如果您不想使用本机 json.Unmarshall,这里有一个使用包 go-simplejson.

的好选择

Documentation