如何从go map对象访问深度嵌入的json对象?

时间:2014-12-22 01:41:55

标签: arrays json dictionary struct go

我是新手,我了解如何将json数据编组为自定义预定义的Struct类型,但我目前正在使用一个可以拥有动态密钥&每次通话的价值观。我可以将这些动态数据编组到地图/界面中,没问题,但我对如何访问深度嵌套在数组中的项目感到有点迷失。

以下是我与USDOL网站合作的示例JSON

    {
    "name": "osha-establishment",
    "count": 15,
    "frequency": "Manual Crawl",
    "version": 4,
    "newdata": true,
    "lastrunstatus": "success",
    "lastsuccess": "Mon Dec 08 2014 11:19:57 GMT+0000 (UTC)",
    "thisversionstatus": "success",
    "results": {
                    "est_search": [
                                    {
                                    "est_name": "Chipotle Mexican Grill",
                                    "state": "MN",
                                    "activity": {
                                        "href": "https://www.osha.gov/pls/imis/establishment.inspection_detail?id=317911832",
                                        "text": "317911832"
                                    },
                                    "opened": "11/20/2014",
                                    "rid": "0552700",
                                    "type": "Complaint",
                                    "sc": "Partial",
                                    "sic": {
                                        "href": "https://www.osha.gov/pls/imis/sic_manual.display?id=44&tab=description",
                                        "text": "5812"
                                    },
                                    "naics": "722110",
                                    "vio": ""
                                    },
                                    {
                                    "est_name": "Chipotle Mexican Grill, Inc.",
                                    "state": "AZ",
                                    "activity": {
                                        "href": "https://www.osha.gov/pls/imis/establishment.inspection_detail?id=317801066",
                                        "text": "317801066"
                                    },
                                    "opened": "07/14/2014",
                                    "rid": "0950411",
                                    "type": "Complaint",
                                    "sc": "Partial",
                                    "sic": {
                                        "href": "https://www.osha.gov/pls/imis/sic_manual.display?id=44&tab=description",
                                        "text": "5812"
                                    },
                                    "naics": "722211",
                                    "vio": "2"
                                    }
                                ]
                }
    }

我想访问此JSON集中sic个键的值。

这是我的破解代码:

package main

    import (
        "encoding/json"
        "log"
        "net/http"
    )

    func main() {
        resp, err := http.Get("https://www.kimonolabs.com/api/2oowt0xq?apikey=")

        if err != nil {
            // handle error
        }
        defer resp.Body.Close()

        var result map[string]interface{}

        dec := json.NewDecoder(resp.Body)
        if err := dec.Decode(&result); err != nil {
            // handle error
            log.Println("This is an error")
        }

        log.Println(result["results"].(map[string]interface{})["est_search"], err)

    }

非常感谢任何有关如何访问sic值的帮助。

1 个答案:

答案 0 :(得分:1)

要将JSON解码为接口值,Decode将其中一个存储在接口值中:

1. bool, for JSON booleans
2. float64, for JSON numbers
3. string, for JSON strings
4. []interface{}, for JSON arrays
5. map[string]interface{}, for JSON objects
6. nil for JSON null

根据上述规则,

  • result["results"].(map[string]interface{})["est_search"]是 来自JSON数组的[]interface{}(规则4)。
  • 迭代 result["results"].(map[string]interface{})["est_search"].([]interface{}),每个项目都是来自JSON对象的map[string]interface{}(规则5)。

以下是示例代码,我运行它,它似乎与该URL一起使用;

package main

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

func main() {
    resp, err := http.Get("https://www.kimonolabs.com/api/2oowt0xq?apikey=DTgSLPbfOPauuLCXTws5jquLQd0V7kBB")

    if err != nil {
        // handle error
    }   
    defer resp.Body.Close()

    var result map[string]interface{}

    dec := json.NewDecoder(resp.Body)
    if err := dec.Decode(&result); err != nil {
        // handle error
        fmt.Println("This is an error")
    }   

    for _, item := range result["results"].(map[string]interface{})["est_search"].([]interface{}) {
        fmt.Println(item.(map[string]interface{})["sic"])
    }   
}