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

如何在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 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示