gpt4 book ai didi

go - 有没有一种好方法可以不在 json 有效负载中公开某些结构属性?

转载 作者:IT王子 更新时间:2023-10-29 01:13:03 27 4
gpt4 key购买 nike

我真的希望下面的代码能工作,但现在不行,所以我必须手动将值从一个结构设置到另一个结构。

https://play.golang.org/p/yfcsaNJm9M

package main

import "fmt"
import "encoding/json"

type A struct {
Name string `json:"name"`
Password string `json:"password"`
}

type B struct {
A
Password string `json:"-"`
Locale string `json:"locale"`
}

func main() {

a := A{"Jim", "some_secret_password"}
b := B{A: a, Locale: "en"}

data, _ := json.Marshal(&b)
fmt.Printf("%v", string(data))
}

输出...我不想显示 secret 字段

{"name":"Jim","password":"some_secret_password","locale":"en"}

最佳答案

Struct values encode as JSON objects. Each exported struct field becomes a member of the object unless

- the field's tag is "-", or
- the field is empty and its tag specifies the "omitempty" option.

The empty values are false, 0, any nil pointer or interface value, and any array, slice, map, or string of length zero. The object's default key string is the struct field name but can be specified in the struct field's tag value. The "json" key in the struct field's tag value is the key name, followed by an optional comma and options. Examples:

// Field is ignored by this package.
Field int `json:"-"`

// Field appears in JSON as key "myName".
Field int `json:"myName"`

// Field appears in JSON as key "myName" and
// the field is omitted from the object if its value is empty,
// as defined above.
Field int `json:"myName,omitempty"`

// Field appears in JSON as key "Field" (the default), but
// the field is skipped if empty.
// Note the leading comma.
Field int `json:",omitempty"`

所以你的代码应该是:

package main

import "fmt"
import "encoding/json"

type A struct {
Name string `json:"name"`
Password string `json:"password"`
}

type B struct {
A
Password string `json:"password,omitempty"`
Locale string `json:"locale"`
}

func main() {

a := A{"Jim", "some_secret_password"}
b := B{A: a, Locale: "en"}

data, _ := json.Marshal(&b)
fmt.Printf("%v", string(data))
}

https://play.golang.org/p/HdwIssr-oC

关于go - 有没有一种好方法可以不在 json 有效负载中公开某些结构属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38494274/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com