I'm trying to convert go structures to JSON. I thought I knew how to do it, but I'm confused by the output of this program. What am I missing?
package main
import "fmt"
import "encoding/json"
type Zoo struct {
name string
animals []Animal
}
type Animal struct {
species string
says string
}
func main() {
zoo := Zoo{"Magical Mystery Zoo",
[]Animal {
{ "Cow", "Moo"},
{ "Cat", "Meow"},
{ "Fox", "???"},
},
}
zooJson, err := json.Marshal(zoo)
if (err != nil) {
fmt.Println(err)
}
fmt.Println(zoo)
fmt.Println(zooJson)
}
Output:
{Magical Mystery Zoo [{Cow Moo} {Cat Meow} {Fox ???}]}
[123 125]
Expected Output (something along the lines of):
{Magical Mystery Zoo [{Cow Moo} {Cat Meow} {Fox ???}]}
{
"name" : "Magical Mystery Zoo",
"animals" : [{
"name" : "Cow",
"says" : "moo"
}, {
"name" : "Cat",
"says" : "Meow"
}, {
"name" : "Fox",
"says" : "???"
}
]
}
Where is [123 125]
coming from?
Appreciate the help!
The result of marshaling is []byte
so 123
and 125
is ascii for {
and }
Struct fields have to be exported for marshaling to work:
Each exported struct field becomes a member of the object
Your problems is in unexported (call it non-public if you want) fields in your structs. Here is the example on Go Play how you can fix it.
Also, if you don't like how your JSON fields named (capital letter in the most cases) you can change them with a struct tags (see json.Marshal doc).
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