Search code examples
jsongotwitter

How to parse huge json in Golang


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 !


Solution

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