14

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?

2 Answers 2

23

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"})
}
Sign up to request clarification or add additional context in comments.

Comments

21

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.