how to set json tag with a variable in golang?

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

how to set json tag with a variable in golang?

问题

有没有一种方法可以设置结构体的字段标签?
例如:

type contact struct {
    Mail string `json:"contact"`
}

newStruct := setTag(temp, "Mail", "mail")

data, _ := json.Marshal(qwe)
fmt.Println(data)

并且它接受以下有效载荷:

{
    "mail": "blabla"
}
英文:

is there a way to set field tag of a struct ?
for example :

type contact struct {
    Mail string `json:"contact"`
}

newStruct := setTag(temp, "Mail", "mail")

data, _ := json.Marshaller(qwe)
fmt.Println(data)

and it accepts this payload:

{
    "mail": "blabla"
}

答案1

得分: 4

看起来你想让你的 JSON 的键是一个变量。你可以使用 map 数据类型来实现这个目的。

package main

import "fmt"
import "encoding/json"

func main() {
    asd := "mail"
    qwe := make(map[string]string)

    qwe[asd] = "jack"

    data, _ := json.Marshal(qwe)
    fmt.Println(string(data))  // 输出 "{mail: jack}"
}

<kbd>
<a href="http://play.golang.org/p/a2O_TvNImh">playground</a>
</kbd>

英文:

Looks like you want your key of the json to be a variable. You can do this by using the map data type.

package main

import &quot;fmt&quot;
import &quot;encoding/json&quot;

func main() {
	asd := &quot;mail&quot;
	qwe := make(map[string]string)

	qwe[asd] = &quot;jack&quot;

	data, _ := json.Marshal(qwe)
	fmt.Println(string(data))  // Prints &quot;{mail: jack}&quot;
}

<kbd>
<a href="http://play.golang.org/p/a2O_TvNImh">playground</a>
</kbd>

答案2

得分: 0

你必须导出该密钥。工作示例

Godoc中的json.Marshal包的说明中可以看到:

结构体值被编码为JSON对象。除非:

  • 字段的标签是“-”,或者
  • 字段为空并且其标签指定了“omitempty”选项,

否则每个导出的结构体字段都成为对象的成员。

英文:

You have to export the key. Working example

From godoc for package json.Marshal,

> 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.

huangapple
  • 本文由 发表于 2016年4月2日 06:22:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/36366707.html
匿名

发表评论

匿名网友

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

确定