Reputation: 4409
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?
Upvotes: 1
Views: 551
Reputation: 1518
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))
}
Upvotes: 1