在Go语言中,是否可以动态转换JSON变量名?

huangapple go评论71阅读模式
英文:

Is it possible to convert JSON variable names on-the-fly in go?

问题

我目前正在实现一个将复杂结构打印成JSON的函数。它需要将变量名转换为小写,这意味着需要在各个地方添加大量的JSON标签。我尝试将结构转换为map,然后更改大小写并转换回来,但这会将int64转换为float64,并且还会弄乱其他一些东西。

有没有一种简便的方法在Go中实现即时转换JSON变量名的方式?

英文:

I'm currently implementing some function that prints a complex structure into JSON. It needs the variable names to be lower-case, which would mean putting a lot of JSON tags all over the place. I tried converting the structure to map, then changing the capitalisation and converting it back, but that converted int64s into float64s and messed a few other things up.

Is there some way to easily convert JSON variable names on-the-fly in go?

答案1

得分: 1

如果地图不适用于您,JSON标签可能是您的最佳选择。

否则,您需要手动修改json.Marshal的输出,它是一个[]byte类型的数据,将其更改为字符串,然后解析并将所有键转换为小写。

英文:

JSON Tags would the your best option, if maps are not an option for you.

Else you would need to manually modify the output of json.Marshal, which is a []byte change it to a string, parse through it and convert all the keys to lower case.

huangapple
  • 本文由 发表于 2016年11月17日 15:17:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/40648848.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定