Go struct to json produces empty document

I’ve tried each and every example I could find on the web to serialize my custom struct into a JSON document, and everyone returns an empty ( { } ) document, and I cannot get why…

Sample code, with my struct:

type dbCredsStruct struct {
	hostname   string `json:"hostname"`
	rootUsr    string `json:"rootusr"`
	rootPasswd string `json:"rootpasswd"`
	port       int    `json:"port"`

func creds2json(jsonFile string, creds dbCredsStruct) {
	c := dbCredsStruct{hostname: "hostname", rootUsr: "rootusr", rootPasswd: "q1w2e3", port: 65432}
	jStream, err := json.Marshal(c)
	if err != nil {
		fmt.Println("Error", err)

	//os.WriteFile(jsonFile, jStream, 0644)

Here, for simplicty, I ignore creds2json()'s parameters and manually populate c with the struct.

The fmt.Println()function will output {} here.

In the debugger, if examine c everything looks good. jstream is of type []uint8 with 2 elements: uint8 123 and uint8 125.

Any idea on what’s going on ??

1 Like

Go doesn’t use access modifiers like public or private and instead uses capitalization to mark a name as visible to other packages. The json package cannot see the hostname field in your dbCredsStruct, so it is ignored. The fix is to rename the fields to use uppercase characters:

type dbCredsStruct struct {
	Hostname   string `json:"hostname"`
	RootUsr    string `json:"rootusr"`
	RootPasswd string `json:"rootpasswd"`
	Port       int    `json:"port"`
1 Like

ohhh… this is the second time I get myself bit with the export-capitalize-the-first-letter thing !!!

Thanks, that solved it ! I knew something was dead wrong in my struct, but never thought of the Capitalize thing. You see, out of sheer frustration I was willing to move from JSON to YAML, and the same thing happened.

Thanks for the quick reply @skillian