user3918985
user3918985

Reputation: 4409

Go: Marshal empty struct into json

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

Answers (1)

Logiraptor
Logiraptor

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

Related Questions