Search code examples
jsongosyntactic-sugar

Go - constructing struct/json on the fly


In Python it is possible to create a dictionary and serialize it as a JSON object like this:

example = { "key1" : 123, "key2" : "value2" }
js = json.dumps(example)

Go is statically typed, so we have to declare the object schema first:

type Example struct {
    Key1 int
    Key2 string
}

example := &Example { Key1 : 123, Key2 : "value2" }
js, _ := json.Marshal(example)

Sometimes object (struct) with a specific schema (type declaration) is needed just in one place and nowhere else. I don't want to spawn numerous useless types, and I don't want to use reflection for this.

Is there any syntactic sugar in Go that provides a more elegant way to do this?


Solution

  • You can use a map:

    example := map[string]interface{}{ "Key1": 123, "Key2": "value2" }
    js, _ := json.Marshal(example)
    

    You can also create types inside of a function:

    func f() {
        type Example struct { }
    }
    

    Or create unnamed types:

    func f() {
        json.Marshal(struct { Key1 int; Key2 string }{123, "value2"})
    }