go-lumber icon indicating copy to clipboard operation
go-lumber copied to clipboard

Batch.Events should contains json.RawMessage, not interface{}

Open athoune opened this issue 8 years ago • 2 comments

Hand casting each key of a complex map[string]interface{} is very painful.

athoune avatar Jun 14 '17 17:06 athoune

With easyjson, I can print unmarshaled value, but can return nothing

invalid indirect of v (type interface {})

If I cast initial value, it crash with a runtime error.

athoune avatar Jun 14 '17 21:06 athoune

I know it's an old thread, but for anyone wondering what to do... You could simply marshal the interface{} back into a JSON string an then unmarshal into a struct. It may not be the fastest solution, but if you know upfront what the JSON structure is then it may be an interesting alternative:

package main

import (
        "encoding/json"
        "log"
)

func main() {
        // Using the blob from the json.Unmarshal documentation example...
        var jsonBlob = []byte(`[
        {"Name": "Platypus", "Order": "Monotremata"},
        {"Name": "Quoll",    "Order": "Dasyuromorphia"}
]`)

        // Unmarshal into empty interface
        var event interface{}
        err := json.Unmarshal(jsonBlob, &event)
        if err != nil {
                log.Fatal("Unable to unmarshal:", err)
        }
        log.Println("Empty interface:", event) // <-- this is what you get from go-lumber

        // Marshal back into JSON string
        jsonString, err := json.Marshal(event)
        if err != nil {
                log.Fatal("Unable to marshal:", err)
        }
        log.Println("JSON string:", string(jsonString))

        // Unmarshal into struct
        type Animal struct {
                Name  string
                Order string
        }
        var animals []Animal
        json.Unmarshal(jsonString, &animals)
        log.Println("Animals:", animals)
}

gwijnja avatar Apr 24 '20 15:04 gwijnja