dongnanke4106 2017-01-23 01:27
浏览 142
已采纳

如何在Golang中解析巨大的json

I'm new to Golang and I am trying to parse large json like the ones you get from an API which have lots of data. The documentation explains how to do this with any json:

b := []byte(`{"Name":"Wednesday","Age":6,"Parents":["Gomez","Morticia"]}`)
var f interface{}
err := json.Unmarshal(b, &f)
m := f.(map[string]interface{})

This works fine, but when I use a json that I get from the Twitter API, like the one at the end of the reference on the Twitter dev site I get this error:

interface conversion: interface {} is []interface {}, not map[string]interface {}

I know that there are similar questions but I couldn't find the answer. Can someone recommend me the better way to solve this?

My go version go1.6.2 linux/amd64.

Thanks !

  • 写回答

1条回答 默认 最新

  • dongou6632 2017-01-23 02:09
    关注

    In this case you are not unmarshalling a single JSON object, but an array of JSON objects which is why you're having an issue parsing the API response. The error your seeing this is telling you the actual type of f. The other example worked because it is a single JSON object, which can be mapped as a map[string]interface{} Take a look at this:

    var f []interface{}
    err := json.Unmarshal(str, &f)
    if err != nil {
        fmt.Println(err)
        return
    }
    
    for _, v := range f {
        z := v.(map[string]interface{})
        for k2, v2 := range z {
            fmt.Println("Key:", k2, "Value:", v2)
        }
    }
    

    f should be of type []interface{} an array of interfaces. Depending on how you plan on parsing the API response, you can do something like I'm doing in the for loop to present each key, value pair.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵