Max Malysh
Max Malysh

Reputation: 31545

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?

Upvotes: 14

Views: 10849

Answers (2)

Ainar-G
Ainar-G

Reputation: 36189

You could use an anonymous struct type.

example := struct {
    Key1 int
    Key2 string
}{
    Key1: 123,
    Key2: "value2",
}
js, err := json.Marshal(&example)

Or, if you are ready to lose some type safety, map[string]interface{}:

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

Upvotes: 20

Caleb
Caleb

Reputation: 9458

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

Upvotes: 23

Related Questions