2017-01-23 01:27
浏览 124


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 {
    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.

    解决 无用
    打赏 举报

相关推荐 更多相似问题