英文:
How to marshal field starting with underscore to JSON [Golang]
问题
Go的encoding/json
包具有一些出色的JSON编组功能,就我所需而言,它完全符合我的要求。但是,当我想尝试编组要插入MongoDB实例的内容时,问题就出现了。
MongoDB将_id
视为索引标识符,但Go的JSON包只编组导出字段,因此当我保存时,MongoDB会为文档创建自己的ID,而我并不希望如此,而且我甚至还没有开始测试将其解组为结构体时可能产生的影响。
有没有办法使JSON编组器包括以下划线开头的字段,而无需编写全新的编组器?
英文:
Go's encoding/json
package has some brilliant JSON marshalling functionality, and for all intents and purposes it's exactly what I need. But the problem arises when I want to try and marshal something I want to insert into a MongoDB instance.
MongoDB understands _id
as an indexed identifier, but Go's JSON package only marshals exported fields so MongoDB creates its own ID for the document when I save, which I do not want, and I haven't even begun to test the implications it will have unmarshalling to a struct.
Is there a way to make the JSON marshaller include fields beginning with an underscore without writing a whole new one?
答案1
得分: 5
你可以轻松地重命名字段。Go语言的字段名称应以大写字母开头以便导出,但JSON名称可以是符合JSON规范的任何内容。
以下是一个借用自encoding/json包文档的示例:
package main
import (
"encoding/json"
"fmt"
"os"
)
func main() {
type ColorGroup struct {
ID int `json:"_id"`
Name string
Colors []string
}
group := ColorGroup{
ID: 1,
Name: "Reds",
Colors: []string{"Crimson", "Red", "Ruby", "Maroon"},
}
b, err := json.Marshal(group)
if err != nil {
fmt.Println("error:", err)
}
os.Stdout.Write(b)
}
希望对你有帮助!
英文:
You can easily rename the fields. The Go name should start with an uppercase to be exported, but the json name can be anything compliant with json.
Here is an example borrowed to the encoding/json package documentation:
package main
import (
"encoding/json"
"fmt"
"os"
)
func main() {
type ColorGroup struct {
ID int `json:"_id"`
Name string
Colors []string
}
group := ColorGroup{
ID: 1,
Name: "Reds",
Colors: []string{"Crimson", "Red", "Ruby", "Maroon"},
}
b, err := json.Marshal(group)
if err != nil {
fmt.Println("error:", err)
}
os.Stdout.Write(b)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论