Reputation: 15502
How can I unmarshall json into a Go struct and omit a specific field? The docs say I can tag a field with json: "-"
to omit it, but this doesn't appear to do anything:
package main
import (
"encoding/json"
"fmt"
)
var data = []byte(`{"bar": true, "baz": true}`)
type Foo struct {
Bar bool `json: "bar"`
Baz bool `json: "-"`
}
func main() {
var foo Foo
json.Unmarshal(data, &foo)
fmt.Println(foo)
}
prints {true, true}
If tagging the Baz
field with json: "-"
worked, I would expect to {true, false}
to print. What went wrong?
Upvotes: 1
Views: 95
Reputation: 15502
Another option is to not export the fields you want to omit. Note the lowercase baz
in the struct definition:
package main
import (
"encoding/json"
"fmt"
)
var data = []byte(`{"bar": true, "baz": true}`)
type Foo struct {
Bar bool
baz bool
}
func main() {
var foo Foo
json.Unmarshal(data, &foo)
fmt.Println(foo)
}
Prints
{true false}
Upvotes: 1
Reputation: 471
The space seems to matter:
Baz bool `json:"-"`
Prints:
{true false}
Upvotes: 4