Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

My structures are not marshalling into json [duplicate]

Tags:

json

go

I am using Go 1.0.3 on Mac OS X 10.8.2, and I am experimenting with the json package, trying to marshal a struct to json, but I keep getting an empty {} json object.

The err value is nil, so nothing is wrong according to the json.Marshal function, and the struct is correct. Why is this happening?

package main

import (
  "encoding/json"
  "fmt"
)

type Address struct {
  street string
  extended string
  city string
  state string
  zip string
}

type Name struct {
  first string
  middle string
  last string
}

type Person struct {
  name Name
  age int
  address Address
  phone string
}

func main() {
  myname := Name{"Alfred", "H", "Eigenface"}
  myaddr := Address{"42 Place Rd", "Unit 2i", "Placeton", "ST", "00921"}
  me := Person{myname, 24, myaddr, "000 555-0001"}

  b, err := json.Marshal(me)

  if err != nil {
    fmt.Println(err)
  }

  fmt.Println(string(b))    // err is nil, but b is empty, why?
  fmt.Println("\n")
  fmt.Println(me)           // me is as expected, full of data
}
like image 829
tlehman Avatar asked Mar 16 '13 16:03

tlehman


People also ask

What is JSON marshaling?

Go's terminology calls marshal the process of generating a JSON string from a data structure, and unmarshal the act of parsing JSON to a data structure.

What is JSON marshalling and Unmarshalling Golang?

In Golang, struct data is converted into JSON and JSON data to string with Marshal() and Unmarshal() method. The methods returned data in byte format and we need to change returned data into JSON or String. In our previous tutorial, we have explained about Parsing JSON Data in Golang.


2 Answers

You have to make the fields that you want to marshal public. Like this:

type Address struct {
  Street string
  Extended string
  City string
  State string
  Zip string
}

err is nil because all the exported fields, in this case there are none, were marshalled correctly.

Working example: https://play.golang.org/p/9NH9Bog8_C6

Check out the docs http://godoc.org/encoding/json/#Marshal

like image 74
lukad Avatar answered Oct 02 '22 22:10

lukad


Note that you can also manipulate what the name of the fields in the generated JSON are by doing the following:

type Name struct {
  First string `json:"firstname"`
  Middle string `json:"middlename"`
  Last string `json:"lastname"` 
}
like image 44
Camilo Crespo Avatar answered Oct 02 '22 21:10

Camilo Crespo