Home >Backend Development >Golang >How to Define Multiple Tags in Go Structs for MongoDB and JSON Marshaling?

How to Define Multiple Tags in Go Structs for MongoDB and JSON Marshaling?

Linda Hamilton
Linda HamiltonOriginal
2024-12-14 14:54:15676browse

How to Define Multiple Tags in Go Structs for MongoDB and JSON Marshaling?

Multiple Tag Definitions in Structs

When querying MongoDB using a struct, one may require multiple name tags to encode and decode the data while respecting the database's conventions (e.g., "pageId" in MongoDB) and JSON's desired formatting ("pageId").

In the provided code, attempting to separate tag strings using commas is the cause of the issue. The correct approach involves using spaces as separators.

type Page struct {
    PageId string                 `bson:"pageId" json:"pageId"`
    Meta   map[string]interface{} `bson:"meta" json:"meta"`
}

As stated in the documentation for the reflect package:

"By convention, tag strings are a concatenation of optionally space-separated key:"value" pairs."

This allows for the definition of multiple name tags in a struct, enabling it to conform to different naming conventions as required.

The above is the detailed content of How to Define Multiple Tags in Go Structs for MongoDB and JSON Marshaling?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn