Marshaling nested types

Here is my code

package main

import (

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

type extended struct {
	tn map[string]string

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


This is what I am getting


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


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.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.