fatih/structtag

Can I modify the tag of the original structure

chendongming0625 opened this issue · 1 comments

hello,Can I modify the tag of the original structure?
for example:

func main(){
type Student struct {
Name string json:"name,omitempty"
}

tag := reflect.TypeOf(Student{}).Field(0).Tag
tags, err := structtag.Parse(string(tag))
jsonTag, err := tags.Get("json")
if err != nil {
	panic(err)
}
jsonTag.Name = "student_name"
jsonTag.Options = nil
tags.Set(jsonTag)
if err!=nil{
	fmt.Println(err)
	return
}
stu:=Student{
	Name:"xiaoming",
}
data,err:=json.Marshal(stu)
fmt.Println(string(data))

}
output {"name":"xiaoming"}

But what I want to output is {"student_name":"xiaoming"}
Does this package support you? What should you do if it supports you?

fatih commented

Hi @chendongming0625

Unfortunately this is not supported by this package. This package let's you examine and parse struct tags. However what you want is to modify the struct fields. If you want to decode it in JSON, there is already support for that:

package main

import (
	"encoding/json"
	"fmt"
)

type Student struct {
	Name string `json:"student_name,omitempty"`
}

func main() {
	stu := Student{
		Name: "xiaoming",
	}
	data, err := json.Marshal(stu)
	if err != nil {
		panic(err)
	}

	fmt.Println(string(data))
}

This outputs:

{"student_name":"xiaoming"}

play link: https://play.golang.org/p/B6ymQEtQTAv
Closing this issue and thanks again for the feedback.