Max Heiber
Max Heiber

Reputation: 15502

How can I omit a field when importing JSON?

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?

Go Playground link

Upvotes: 1

Views: 95

Answers (2)

Max Heiber
Max Heiber

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}

GO

Upvotes: 1

oliveromahony
oliveromahony

Reputation: 471

The space seems to matter:

Baz bool `json:"-"`

Prints:

{true false}

Go

Upvotes: 4

Related Questions