Gotcha: Field casing is important when marshalling structs to JSON in Go

Featured image for sharing metadata for article

I'm trying to learn a bit of Go, and while working through a few things, I spotted a little gotcha with marshalling JSON from structs.

In tutorials and example code, I've seen a mix of structs with uppercase field names:

type User struct {
Name string
}

But also some with lowercase field names:

type User struct {
name string
}

Thinking that this didn't matter, I started using lowercase names, as I'm more used to lowercase, as a Java developer, and to my surprise, found that serialising this to JSON didn't work.

The following code:

package main

import (
	"encoding/json"
	"fmt"
)

type User struct {
  name string
}

func main() {
	r, err := json.Marshal(User{name: "Bob"})
	if err != nil {
		panic(err)
	}
	fmt.Println(string(r))
}

Would return me the following output:

{}

It turns out that this is an expected case, because according to this answer on StackOverflow:

This is because only fields starting with a capital letter are exported, or in other words visible outside the curent package (and in the json package in this case).

Therefore, the fix here was to make the following change, so the Name field would appear in the JSON as the $.name property:

 type User struct {
-  name string
+  Name string `json:"name"`
 }

Written by Jamie Tanna's profile image Jamie Tanna on , and last updated on .

Content for this article is shared under the terms of the Creative Commons Attribution Non Commercial Share Alike 4.0 International, and code is shared under the Apache License 2.0.

#blogumentation #go #json.

Also on:

This post was filed under articles.

Interactions with this post

Interactions with this post

Below you can find the interactions that this page has had using WebMention.

Have you written a response to this post? Let me know the URL:

Do you not have a website set up with WebMention capabilities? You can use Comment Parade.