Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang multiple json tag names for one field

Tags:

json

struct

go

tags

It it possible in Golang to use more than one name for a JSON struct tag ?

type Animation struct {
    Name    string  `json:"name"`
    Repeat  int     `json:"repeat"`
    Speed   uint    `json:"speed"`
    Pattern Pattern `json:"pattern",json:"frames"`
}
like image 201
William Poussier Avatar asked Aug 06 '16 22:08

William Poussier


People also ask

Can you have multiple tag strings in struct in field in go?

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.


1 Answers

you can use multiple json tag with third part json lib like github.com/json-iterator/go coding like below:

package main

import (
    "fmt"
    "github.com/json-iterator/go"
)

type TestJson struct {
    Name string `json:"name" newtag:"newname"`
    Age  int    `json:"age" newtag:"newage"`
}

func main() {

    var json = jsoniter.ConfigCompatibleWithStandardLibrary
    data := TestJson{}
    data.Name = "zhangsan"
    data.Age = 22
    byt, _ := json.Marshal(&data)
    fmt.Println(string(byt))

    var NewJson = jsoniter.Config{
        EscapeHTML:             true,
        SortMapKeys:            true,
        ValidateJsonRawMessage: true,
        TagKey:                 "newtag",
    }.Froze()

    byt, _ = NewJson.Marshal(&data)
    fmt.Println(string(byt))
}

output:

    {"name":"zhangsan","age":22}
    {"newname":"zhangsan","newage":22}
like image 167
Zhang Avatar answered Sep 18 '22 13:09

Zhang