Marshaling nested types

Here is my code

package main

import (
	"encoding/json"
	"fmt"
)

type Details struct {
	ID string `json:"id"`
}

type extended struct {
	Details
	tn map[string]string
}

func main() {
	b, _ := json.Marshal(extended{
		Details:  Details{
			ID: "foo",
		},
		tn: map[string]string{
			"test": "bar",
		},
	})

	fmt.Println(string(b))
}

This is what I am getting

{"id":"foo"}

And I want to get this

{"id":"foo", "test":"bar"}

Thanks for your help.

json.Marshal only marshals public struct members: Go Playground - The Go Programming Language

2 Likes

I dont want to print TN in the raw message. Your code prints {"id":"foo","TN":{"test":"bar"}} and I want {"id":"foo","test":"bar"}

1 Like

You want custom marshaling. Write a MarshalJSON() ([]byte, error) method for your Extended type. json package - encoding/json - Go Packages

1 Like

tn needs to be changed to Tn so that it is exported.
You can not marshall private fields.