Go has a really nice way to convert to JSON. To convert from a Go type to JSON is called marshalling.
Let's look at an example:
type person struct {
Name string
}
func main() {
m := person{Name: "Mike"}
mj, _ := json.Marshal(m)
fmt.Println(string(mj)) //{"Name":"Mike"}
}
Here you can see that we have defined our custom type person
, and created m
which has type person
. The json.Marshal
function will use the fields in your type as the key names. You can also use standard Go types like strings, ints, structs etc. Lets make this example slightly more complicated to explain a few other details:
type person struct {
Name string `json:"First name"`
age int
}
func main() {
m := person{Name: "Mike", age: 25}
mj, _ := json.Marshal(m)
fmt.Println(string(mj)) //{"First name":"Mike"}
}
This time we have a second field on our type without an uppercase letter at the start. This means that this field is not exported, and as a result, json.Marshal
does not put this field into the JSON. The other thing that we've added here is a “tag” ( `json:”First name”`
). This means that instead of using Name
as our JSON key, "First name”
will be used instead.
You can see this example here.
Self taught software developer with 11 years experience excelling at JavaScript/Typescript, React, Node and AWS.
I love learning and teaching and have mentored several junior developers over my career. I find teaching is one of the best ways to solidify your own learning, so in the past few years I've been maintaining a technical blog where I write about some things that I've been learning.
I'm passionate about building a teams culture and processes to make it efficient and satisfying to work in. In many roles I have improved the quality and reliability of the code base by introducing or improving the continuous integration pipeline to include quality gates.