Logan Shire Logan Shire - 1 year ago 90
JSON Question

JSON decode into struct as interface{} yields map[string]interface{}, not struct

Here is a go playground replicating the issue:

Basically, I'm trying to write a function that takes a struct and returns a function that can decode http requests as that type. Unfortunately some type information is being lost and the type being returned is a map[string]interface{} and not the correct struct type. How can I communicate the correct type to the JSON decoder? Would JSON unmarshal work better?

Answer Source

This seems to work:


func requestParser(i interface{}) parser {
    return func(r io.Reader) (interface{}, error) {
        return reflect.ValueOf(i).Elem(), nil

func main() {
    var foo Foo
    s := "{\"Name\":\"Logan\"}"
    p := requestParser(&foo)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download