Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

json.Marshal returning strange results

Tags:

json

go

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!

like image 992
Greg Prisament Avatar asked Dec 07 '22 03:12

Greg Prisament


2 Answers

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

like image 83
Arjan Avatar answered Dec 15 '22 11:12

Arjan


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).

like image 27
Kavu Avatar answered Dec 15 '22 10:12

Kavu