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
Release: 2024-12-14 14:54:15
Original
678 people have browsed it

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"`
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template