unmarshal generic json in Go

Viewed 15011

I'm a new Go programmer (From Java) and I would like to reproduce a generic way which is esay to use in Java.

I want to create some function which allow me to do an Unmarshal on a JSON string in order to avoid code duplicity.

This is my current code which is not working :

type myStruct1 struct {
    id string
    name string
}

func (obj myStruct1) toString() string {
    var result bytes.Buffer
    result.WriteString("id : ")
    result.WriteString(obj.id)
    result.WriteString("\n")
    result.WriteString("name : ")
    result.WriteString(obj.name)

    return result.String()
}

func main() {

    content := `{id:"id1",name="myName"}`
    object := myStruct1{}
    parseJSON(content, object)

    fmt.Println(object.toString()) 
}

func parseJSON(content string, object interface{}) {
    var parsed interface{}
    json.Unmarshal([]byte(content), &parsed)
}

This code, on run, returns me this :

id : 
name : 

Do you have any idea ?

Thanks

6 Answers

To parse "generic JSON" when you have no idea what schema it has:

    var parsed interface{}
    err := json.Unmarshal(jsonText, &parsed)

The returned interface{} in parsed will be a map[string]interface{} or []interface{}.

You can test the type and react accordingly.

import (
    "encoding/json"
    "fmt"
)

func test(jsonText []byte) {
    // parsing
    var parsed interface{}
    err := json.Unmarshal(jsonText, &parsed)
    if err != nil {
        panic(err) // malformed input
    }

    // type-specific logic
    switch val := parsed.(type) {
    case map[string]interface{}:
        fmt.Printf("id:%s name:%s\n", val["id"], val["name"])
    case []interface{}:
        fmt.Printf("list of %d items\n", len(val))
    default:
        panic(fmt.Errorf("type %T unexpected", parsed))
    }
}

You can also set the file as an Object with dynamic properties inside another struct. This will let you add metadata and you read it the same way.

type MyFile struct {
    Version string
    Data  map[string]interface{}
}
Related