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
Reading and Writing JSON Files in Go It is actually pretty simple to read and write data to and from JSON files using the Go standard library. For writing struct types into a JSON file we have used the WriteFile function from the io/ioutil package. The data content is marshalled/encoded into JSON format.
JSON is a widely used format for data interchange. Golang provides multiple encoding and decoding APIs to work with JSON including to and from built-in and custom data types using the encoding/json package. Data Types: The default Golang data types for decoding and encoding JSON are as follows: bool for JSON booleans.
Go offers built-in support for JSON encoding and decoding, including to and from built-in and custom data types. We'll use these two structs to demonstrate encoding and decoding of custom types below. Only exported fields will be encoded/decoded in JSON.
You are missing two things.
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"}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With