ray
ray

Reputation: 193

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

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.

Upvotes: 9

Views: 9330

Answers (2)

Jon Erickson
Jon Erickson

Reputation: 114826

What is possible though, with 2 identically laid out structs (namin, types and ordering of fields needs to match exactly) is to cast from one to the other. I would be very cautious of doing this though and make sure the 2nd type (bar in your example) is unexported to prevent from being used elsewhere.

https://play.golang.org/p/y8EH1U9_3jN

Upvotes: 6

icza
icza

Reputation: 417402

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).

Upvotes: 5

Related Questions