在导入JSON时,如何省略一个字段?

huangapple go评论95阅读模式
英文:

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}。出了什么问题?

Go Playground链接

英文:

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

答案1

得分: 4

空间似乎很重要:

Baz bool `json:"-"`

打印:

{true false}

Go

英文:

The space seems to matter:

Baz bool `json:"-"`

Prints:

{true false}

Go

答案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}

GO

英文:

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

huangapple
  • 本文由 发表于 2015年4月20日 08:13:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/29737416.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定