1

I'm trying to marshal a struct into json. It works when the struct has values. However, I'm unable to access the webpage when the struct has no value:

Go:

type Fruits struct { Apple []*Description 'json:"apple, omitempty"' } type Description struct { Color string Weight int } func Handler(w http.ResponseWriter, r *http.Request) { j := {[]} js, _ := json.Marshal(j) w.Write(js) } 

Is the error because json.Marshal cannot marshal an empty struct?

1
  • What error? You're explicitly ignoring the error. It might help to check it. Also, {[]} is invalid syntax in Go. Commented Oct 5, 2014 at 1:37

1 Answer 1

1

See here: http://play.golang.org/p/k6d6y7TnIQ

package main import "fmt" import "encoding/json" type Fruits struct { Apple []*Description `json:"apple, omitempty"` } type Description struct { Color string Weight int } func main() { j := Fruits{[]*Description{}} // This is the syntax for creating an empty Fruits // OR: var j Fruits js, err := json.Marshal(j) if err != nil { fmt.Println(err) return } fmt.Println(string(js)) } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.