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

deft_code
  • 57,255
  • 29
  • 141
  • 224
Tusshu
  • 1,664
  • 3
  • 16
  • 32
  • possible duplicate of [My structures are not marshalling into json](http://stackoverflow.com/questions/15452004/my-structures-are-not-marshalling-into-json) – deft_code Jun 11 '14 at 21:19

1 Answers1

16

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"}}
fabrizioM
  • 46,639
  • 15
  • 102
  • 119
  • thanks for the answer. Missed public/private distinction by using uppercase, old Java habit... – Tusshu Jun 11 '14 at 17:36