Tusshu
Tusshu

Reputation: 1734

How to create JSON for Go struct

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

Upvotes: 9

Views: 16081

Answers (1)

fabmilo
fabmilo

Reputation: 48330

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"}}

Upvotes: 16

Related Questions