json - 为什么 Go json.Marshal 拒绝这些结构标签? json 标签的正确语法是什么?

标签 json go struct tags marshalling

<分区>

我正在尝试使用 json.Marshal,但它拒绝接受我的结构标签。

我做错了什么?

这是“marshal.go”的源代码

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

package main

import (
    "encoding/json"
    "fmt"
)

type Person struct {
    Name string `json: "name"`
    Age  int    `json: "age"`
}

func main() {
    p := Person{Name: "Alice", Age: 29}
    bytes, _ := json.Marshal(p)
    fmt.Println("JSON = ", string(bytes))
}

我从“go vet marshal.go”得到这些错误信息

./marshal.go:9: struct field tag `json: "name"` not compatible with reflect.StructTag.Get: bad syntax for struct tag value
./marshal.go:10: struct field tag `json: "age"` not compatible with reflect.StructTag.Get: bad syntax for struct tag value

我在运行程序时得到了这个输出。

% ./marshal
JSON =  {"Name":"Alice","Age":29}

注意字段名称匹配 Go 结构并忽略 json 标签。

我错过了什么?

最佳答案

我的天哪!我刚刚弄明白了。 json: 和字段名 "name" 之间不允许有空格。

“go vet”错误消息(“语法错误”)非常无用。

以下代码有效。你能看出区别吗?

package main

import (
    "encoding/json"
    "fmt"
)

type Person struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

func main() {
    p := Person{Name: "Alice", Age: 29}
    bytes, _ := json.Marshal(p)
    fmt.Println("JSON = ", string(bytes))
}

关于json - 为什么 Go json.Marshal 拒绝这些结构标签? json 标签的正确语法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53051979/

相关文章:

json - mongo 2.6.4 中的多个 $near 不起作用

javascript - 如何将父字段名称添加到json对象中新添加的行

java - 将 JSON 与 AES 一起使用会引发 javax.crypto.IllegalBlockSizeException

c - 从 Go 访问类型为 const char * 的 C 数组

C : Load data from file to the linked list

swift - Swift 3 中相互引用的结构

C# 结构数组和赋值性能

python - 删除括号之间的所有最后一个逗号

curl - 如何在 golang 中使用 curl 发送身份验证 token ?

golang 从 stdin 扫描一行数字