duanpi7578 2014-12-22 01:41
浏览 38
已采纳

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

I am new to go and I understand how to marshall json data into custom predefined Struct types but I'm currently working with a JSON set that can have dynamic keys & values with every call. I can marshall this dynamic data into a map/interface no problem but I'm a little lost with how to access the item that are deeply nested in an array.

Here is sample JSON that I'm working with from the USDOL website

    {
    "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"
                                    }
                                ]
                }
    }

I'd like to access the values of the sic keys in this JSON set.

Here is my broke go code:

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)

    }

Any help showing me how to access the sic values would be greatly appreciated.

  • 写回答

1条回答 默认 最新

  • dongleiqiao4906 2014-12-22 03:20
    关注

    To decode JSON into an interface value, Decode stores one of these in the interface value:

    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
    

    According to rules above,

    • result["results"].(map[string]interface{})["est_search"] is []interface{} from JSON array (rule 4).
    • iterate over result["results"].(map[string]interface{})["est_search"].([]interface{}), each item is map[string]interface{} from JSON object (rule 5).

    Here is the example code, I ran it and it seems to work with that 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"])
        }   
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)