tommyd456 tommyd456 - 3 months ago 15
JSON Question

Store struct as string in redis

As Redis only stores strings I would like to know how I can do the equivalent of Javascript's JSON.stringify using Go to convert a Struct into a string.

I have tried typecasting:

string(the_struct)


but this results in an error.

Answer

The encoding/json package can be used to easily convert a struct to JSON string and vice versa (parse a JSON string into a struct).

Simple example (try it on the Go Playground):

type Person struct {
    Name string
    Age  int
}

func main() {
    p := Person{"Bob", 23}

    // Struct -> JSON
    data, err := json.Marshal(&p)
    if err != nil {
        panic(err)
    }
    fmt.Println(string(data))

    // JSON -> JSON
    var p2 Person
    err = json.Unmarshal(data, &p2)
    if err != nil {
        panic(err)
    }
    fmt.Printf("%+v", p2)
}

Output:

{"Name":"Bob","Age":23}
{Name:Bob Age:23}

Notes:

The fields of the struct must be exported (start them with capital letter), else the json package (which uses reflection) will not be able to read/write them.

You can also specify tags for the struct fields to control/fine tune the json marshaling/unmarshaling process, for example to change the names in the JSON text:

type Person struct {
    Name string `json:"name"`
    Age  int    `json:"years"`
}

With this change the output of the above application is the following:

{"name":"Bob","years":23}
{Name:Bob Age:23}

The documentation of the json.Marshal() function details the possibilities provided by the tags.

And by implementing the json.Marshaler and json.Unmarshaler interfaces you can fully customize the marshaling / unmarshaling process.

Also if your struct is not pre-defined (e.g. you don't know the fields in advance), you can use a map[string]interface{}. See this answer for details and examples.