json - 无需启动双引号的json标记有效

标签 json go struct

我有一个带有json标签的结构。其中之一是没有开始双引号。在测试过程中,它确实起作用。我想知道为什么并且有没有工具可以捕捉这种错别字?

type req struct {
    Name        string `json:name"`
}

我在go1.13 linux/amd64上。

最佳答案

就像您将完全删除无效标签一样:

type req struct {
    Name string
}

引用 json.Marhsal() :

Struct values encode as JSON objects. Each exported struct field becomes a member of the object, using the field name as the object key, unless the field is omitted for one of the reasons given below.



如果标签无效,则将其视为没有标签,并且默认情况下使用字段名称。
go vet报告不遵循 reflect.StructTag 概述的“惯例”的标签:

By convention, tag strings are a concatenation of optionally space-separated key:"value" pairs. Each key is a non-empty string consisting of non-control characters other than space (U+0020 ' '), quote (U+0022 '"'), and colon (U+003A ':'). Each value is quoted using U+0022 '"' characters and Go string literal syntax.



Go Playground上运行它(也运行go vet):
./prog.go:9:2: struct field tag `json:name"` not compatible with reflect.StructTag.Get: bad syntax for struct tag value
Go vet exited.

{"Name":"john"} <nil>

关于json - 无需启动双引号的json标记有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59796401/

相关文章:

javascript - 如何用循环输出json?

去测试覆盖,在不同的包上

c++ - 在循环中创建结构的更好方法

c - 将结构体数组作为指针传递

c - 我如何更正这个程序(结构和指针(?))?

jquery - 使用防伪 token 将 JSON 模型发布到 ASP.Net MVC3

ios - Alamofire 完成处理程序返回响应+数据

javascript - 动态定义 JSON - 找不到我做错了什么

go - 如何比较 Go 错误

go - Golang 1.4.1 中 GC 导致的 cpu 核心数是多少