Unable to print nested struct golang with json.MarshalIndent

Issue

package main

import (
    "encoding/json"
    "fmt"
)

type Data struct {
    a string
    b int
}

type Project struct {
    Id    int64
    Title string
    Name  string
    Data  Data
}

func main() {
    yourProject := &Project{
        Id:    1,
        Title: "games",
        Name:  "Nayan",
        Data: Data{
            a: "chill",
            b: 1,
        },
    }

    fmt.Println(yourProject.Data.a)
    fmt.Printf("%T\n", yourProject)
    res, _ := json.MarshalIndent(yourProject, "", "\t")
    fmt.Print(string(res))
}

Here I’m trying to print nested struct but half of the struct is printing. The Data sub struct is printed as {}. I want to print it as whole struct. Can someone explain why its happening and help me.
Thanks in advance.

Output

chill
*main.Project
{
    "Id": 1,
    "Title": "games",
    "Name": "Nayan",
    "Data": {}
}

Solution

Only public members of structs are seen and exported by json package method Marshal:

Struct values encode as JSON objects. Each exported struct field
becomes a member of the object, using the field name as the object key

See Marshal documentation.

If you want to see a and b value, you have to export them, and change the name to A and B.

If you want to keep the field name lowercase in your json, use struct field tags, like:

    A string `json:"a"`

E.g.: https://go.dev/play/p/Rd5VdPohd0O

Answered By – Cirelli94

Answer Checked By – David Goodson (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.