英文:
How can I omit a field when importing JSON?
问题
如何将JSON解组为Go结构体并省略特定字段?文档中说可以使用json:"-"
标记字段以省略它,但是这似乎没有起作用:
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)
}
输出结果为{true, true}
如果将Baz
字段标记为json:"-"
,我期望输出结果为{true, false}
。出了什么问题?
英文:
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?
答案1
得分: 4
空间似乎很重要:
Baz bool `json:"-"`
打印:
{true false}
答案2
得分: 1
另一个选项是不导出你想要省略的字段。请注意结构体定义中的小写baz
:
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)
}
输出结果为:
{true false}
英文:
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}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论