Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to have a struct with multiple JSON tags?

Tags:

json

struct

go

I post a request to a server and get a reply in JSON format. I'm able to unmarshal it to a struct. Then I need to create a new JSON file with the same data but different JSON tags.

Example:

In the following code, I get {"name":"Sam","age":20} from a server and unmarshal it to the struct Foo:

type Foo struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

Then I need to change the tag name to employee_name and omit age:

type Bar struct {
    Name string `json:"employee_name"`
    Age  int    `json:"-"`
}

After that I send this modified data to another server.

I know I could just create a new Bar and copy all data into it, but there are a lot of fields. I was wondering if there is a way to attach multiple JSON tags like this:

type Foo struct {
    Name string `json:"name" json:"employee_name"`
    Age  int    `json:"age" json:"-"`
}        

Thanks in advance.

like image 871
ray Avatar asked May 09 '16 14:05

ray


People also ask

Can you have multiple tag strings in struct field?

This meta-data is declared using a string literal in the format key:"value" and are separated by space. That is, you can have multiple tags in the same field, serving different purposes and libraries.

What are struct tags?

A struct tag is additional meta data information inserted into struct fields. The meta data can be acquired through reflection. Struct tags usually provide instructions on how a struct field is encoded to or decoded from a format. Struct tags are used in popular packages including: encoding/json.

What is a Go tag?

Tags are a way to attach additional information to a struct field. The Go spec in the Struct types definition defines tags as. A field declaration may be followed by an optional string literal tag, which becomes an attribute for all the fields in the corresponding field declaration.


1 Answers

It's not possible. The encoding/json package only handles the json key in struct tags. If the json key is listed multiple times (as in your example), the first occurrence will be used (this is implemented in StructTag.Get()).

Note that this is an implementation restriction of the encoding/json package and not that of Go. One could easily create a similar JSON encoding package supporting either multiple tag keys (e.g. json1, json2) or multiple occurrences of the same key (as in your example).

like image 176
icza Avatar answered Nov 02 '22 04:11

icza