9

I am trying to use the Marshal function to create JSON from a Go struct. The JSON created does not contain the Person struct.
What am I missing?

http://play.golang.org/p/ASVYwDM7Fz

type Person struct {
    fn string
    ln string
}
type ColorGroup struct {
    ID     int
    Name   string
    Colors []string
    P      Person
}

per := Person{
    fn: "John",
    ln: "Doe",
}

group := ColorGroup{
    ID:     1,
    Name:   "Reds",
    Colors: []string{"Crimson", "Red", "Ruby", "Maroon"},
    P:      per,
}
b, err := json.Marshal(group)
if err != nil {
    fmt.Println("error:", err)
}
os.Stdout.Write(b)

The output generated is as follows:

{"ID":1,"Name":"Reds","Colors":["Crimson","Red","Ruby","Maroon"],"P":{}}

I don't see Person in the output.
http://golang.org/pkg/encoding/json/#Marshal

1

1 Answer 1

15

You are missing two things.

  1. Only Public fields can be Marshaled to json.
  2. The name written to json is the name of the fieldd. In this case P for the field Person.

Notice that I changed the Fields name to be capital for the Person struct and that I added a tag json on the ColorGroup Struct to indicate that I want that field to be serialized with another name. Is common to tag most of the fields and change the name to lowercase to be in sync with javascript's style.

http://play.golang.org/p/HQQ8r8iV7l

package main

import (
"encoding/json"
"fmt"
"os"
)

func main() {
type Person struct {
    Fn string
    Ln string
}
type ColorGroup struct {
    ID     int
    Name   string
    Colors []string
    P Person `json:"Person"`
}

per := Person{Fn: "John",
            Ln: "Doe",
    }

group := ColorGroup{
    ID:     1,
    Name:   "Reds",
    Colors: []string{"Crimson", "Red", "Ruby", "Maroon"},
    P: per,
}
b, err := json.Marshal(group)
if err != nil {
    fmt.Println("error:", err)
}
os.Stdout.Write(b)
}

Will output

{"ID":1,"Name":"Reds","Colors":["Crimson","Red","Ruby","Maroon"],"Person":{"Fn":"John","Ln":"Doe"}}
Sign up to request clarification or add additional context in comments.

1 Comment

thanks for the answer. Missed public/private distinction by using uppercase, old Java habit...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.