Golang - 无法访问[] interface {}中的地图

时间:2016-04-02 10:27:38

标签: json dictionary go interface

我使用了json.Unmarshal并提取了json内容。然后,我通过使用以下代码设法使[]interface{}更深入一层:

        response, err := http.Get("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=2B2A0C37AC20B5DC2234E579A2ABB11C&steamids=76561198132612090")
        content, err := ioutil.ReadAll(response.Body)
        defer response.Body.Close()
        if err != nil {
            panic(0)
        }

        var decoded map[string]interface{}
        if err := json.Unmarshal(content, &decoded); err != nil {
            panic(0)
        }

        players := decoded["response"].(map[string]interface{})["players"]
        if err != nil {
            panic(0)
        }

可变玩家的类型为[]interface {},内容为[map[personaname:Acidic]]

如何访问此地图?我试过players["personaname"],但这似乎不起作用。有什么想法吗?

2 个答案:

答案 0 :(得分:2)

使用预期的架构定义结构类型将使您在从中获取数据时更轻松:

package main

import "fmt"

//import "net/http"
//import "io/ioutil"
import "encoding/json"

// you don't need to define everything, only what you need
type Player struct {
    Steamid                  string
    Communityvisibilitystate int
    Personaname              string
    Lastlogoff               int64 // time.Unix(Lastlogoff, 0)
    Profileurl               string
    Avatar                   string
    Avatarmedium             string
    Avatarfull               string
    Personastate             int
    Realname                 string
    Primaryclanid            string
    Timecreated              int64 // time.Unix(Timecreated, 0)
    Personastateflags        int
    //Loccountrycode           string // e.g. if you don't need this
}

func main() {
    /*response, err := http.Get("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=2B2A0C37AC20B5DC2234E579A2ABB11C&steamids=76561198132612090")
    if err != nil {
        panic(err)
    }
    content, err := ioutil.ReadAll(response.Body)
    defer response.Body.Close()
    if err != nil {
        panic(0)
    }*/
    content := []byte(`{
    "response": {
        "players": [
            {
                "steamid": "76561198132612090",
                "communityvisibilitystate": 3,
                "profilestate": 1,
                "personaname": "Acidic",
                "lastlogoff": 1459489924,
                "profileurl": "http://steamcommunity.com/id/ari9/",
                "avatar": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/bc/bc50a4065c31c606e51dfad329341b2d1f1ac4d3.jpg",
                "avatarmedium": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/bc/bc50a4065c31c606e51dfad329341b2d1f1ac4d3_medium.jpg",
                "avatarfull": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/bc/bc50a4065c31c606e51dfad329341b2d1f1ac4d3_full.jpg",
                "personastate": 3,
                "realname": "Ari Seyhun",
                "primaryclanid": "103582791440552060",
                "timecreated": 1397199406,
                "personastateflags": 0,
                "loccountrycode": "TR"
            }
        ]

    }
}`)

    var decoded struct {
        Response struct {
            Players []Player
        }
    }
    if err := json.Unmarshal(content, &decoded); err != nil {
        panic(err)
    }

    fmt.Printf("%#v\n", decoded.Response.Players)
}

http://play.golang.org/p/gVPRwLFunF

您还可以time.TimeTimecreatedLastlogoff创建一个新的命名类型,并使用自己的UnmarshalJSON函数,并立即将其转换为time.Time time.Unix()

答案 1 :(得分:0)

玩家是一个JSON数组。因此,您必须将其转换为接口片段。

然后,您可以访问切片的任何元素并将其转换为map[string]interface{}类型。

这是工作示例

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
)

func main() {
    response, err := http.Get("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=2B2A0C37AC20B5DC2234E579A2ABB11C&steamids=76561198132612090")
    content, err := ioutil.ReadAll(response.Body)
    defer response.Body.Close()
    if err != nil {
        panic(0)
    }

    var decoded map[string]interface{}
    if err := json.Unmarshal(content, &decoded); err != nil {
        panic(0)
    }

    players := decoded["response"].(map[string]interface{})["players"]
    if err != nil {
        panic(0)
    }

    sliceOfPlayers := players.([]interface{})
    fmt.Println((sliceOfPlayers[0].(map[string]interface{}))["personaname"])
}