I have an application that can output as JSON or XML depending on the HTTP request headers. I can achieve the correct output for either by adding the correct tags to the structs I'm using, but I can't figure out how to specify the tags for both JSON and XML.
For example, this serializes to correct XML:
type Foo struct {
Id int64 `xml:"id,attr"`
Version int16 `xml:"version,attr"`
}
...and this generates correct JSON:
type Foo struct {
Id int64 `json:"id"`
Version int16 `json:"version"`
}
...but this doesn't work for either:
type Foo struct {
Id int64 `xml:"id,attr",json:"id"`
Version int16 `xml:"version,attr",json:"version"`
}
A struct is a user-defined type that contains a collection of fields. It is used to group related data to form a single unit. A Go struct can be compared to a lightweight class without the inheritance feature. A struct tag is additional meta data information inserted into struct fields.
An optional identifier, called a "tag," gives the name of the structure type and can be used in subsequent references to the structure type. A variable of that structure type holds the entire sequence defined by that type.
We can encode the Struct to JSON using the JSON package in Go. JSON pkg has the Marshal and MarshalIndent function that returns the JSON encoding of the given input. MarshalIndent is like Marshal but applies Indent to format the output.
Tags in Golang. Declaration of struct fields can be enriched by string literal placed afterwards — tag. Tags add meta information used either by current package or external ones. Let’s first recall how struct declarations look like, then we’ll deep dive into tags themselves and we’ll wrap up with couple of use cases.
Using XML in GoLang - GoLang Docs Using XML in GoLang XML is a data-interchange format. It is heavily used alongside with JSON.
There’re more potential uses cases of tags like configuration management, default values for structs, validation, command-line arguments description etc. ( list of well-known struct tags ). Go compiler doesn’t enforce conventional format of struct tags but go vet does that so it’s worth to use it e.g. as a part of CI pipeline.
Go tags are space-separated. From the manual:
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.
So, what you want to write is:
type Foo struct {
Id int64 `xml:"id,attr" json:"id"`
Version int16 `xml:"version,attr" json:"version"`
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With