Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 490
Max Malysh Avatar asked May 07 '15 15:05

Max Malysh


People also ask

Can you write JSON file using Go language?

Reading and Writing JSON Files in GoIt is actually pretty simple to read and write data to and from JSON files using the Go standard library. For writing struct types into a JSON file we have used the WriteFile function from the io/ioutil package. The data content is marshalled/encoded into JSON format.

How do I write JSON data to a file in Golang?

The struct values are initialized and then serialize with the json. MarshalIndent() function. The serialized JSON formatted byte slice is received which then written to a file using the ioutil. WriteFile() function.

How do you write a struct in Golang?

It is followed by the name of the type (Address) and the keyword struct to illustrate that we're defining a struct. The struct contains a list of various fields inside the curly braces. Each field has a name and a type. The above code creates a variable of a type Address which is by default set to zero.

What does JSON Unmarshal do in Golang?

To parse JSON, we use the Unmarshal() function in package encoding/json to unpack or decode the data from JSON to a struct. Unmarshal parses the JSON-encoded data and stores the result in the value pointed to by v.


1 Answers

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"})
}
like image 171
Caleb Avatar answered Oct 01 '22 13:10

Caleb