Multiple JSON tags in Go


Go’s standard JSON library, encoding/json, is very thorough and is good enough for most use cases. Its most used functionalities are Marshal and Unmarshal, which respectively take care of turning a Go struct into its JSON representation and vice versa.

There are, however, situations in which the standard JSON library is simply not enough. One of these situations is wanting to handle several different tags for a single struct. Let’s take a look at an example to understand this problem better:

type Person struct {
	FirstName string `json:"first_name"`
	LastName string `json:"last_name"`
	CurrentAge int `json:"current_age"`
}

The previous struct has three fields, each with a name, a type and a tag. These tags indicate the name each field will have when one of these structs is represented in JSON format.

What would happen if we wanted to support more tags? For example, we may want to use both snake case and camel case when converting to and from JSON. The answer to this problem is jsoniter.

Jsoniter is a different JSON handling library for Go, capable of doing everything encoding/json does and more. It can act as a drop-in replacement that not only has more features, but is also considerably faster.

The following code offers a solution to the problem stated earlier:

type Person struct {
	FirstName string `snake:"first_name" camel:"firstName"`
	LastName string `snake:"last_name" camel:"lastName"`
	CurrentAge int `snake:"current_age" camel:"currentAge"`
}

func print() {
	snakeCaseJSON := jsoniter.Config{TagKey: "snake"}.Froze()
	camelCaseJSON := jsoniter.Config{TagKey: "camel"}.Froze()

	p := &Person{"Pepito", "Perez", 32}

	result, _ := snakeCaseJSON.Marshal(p)
	fmt.Println(string(result))

	result, _ = camelCaseJSON.Marshal(p)
	fmt.Println(string(result))
}

And its output:

{"first_name":"Pepito","last_name":"Perez","current_age":32}
{"firstName":"Pepito","lastName":"Perez","currentAge":32}

As you can see, we were able to define and use more than one set of tags for the attributes of our struct. Using jsoniter, we can create different APIs of the library’s methods, with customized configurations. In this case, the TagKey is the configuration we want to change. By doing this, we’re able to define several tags, and use any of them when we Marshal or Unamrshal our structs.

go  json  jsoniter