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?
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.
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.
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.
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.
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"})
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With