Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
athoune opened this issue Jun 14, 2017 · 2 comments
Open

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

athoune opened this issue Jun 14, 2017 · 2 comments

Comments

@athoune
Copy link

athoune commented Jun 14, 2017

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

@athoune
Copy link
Author

athoune commented Jun 14, 2017

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.

@gwijnja
Copy link

gwijnja commented Apr 24, 2020

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)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants