如何在Golang中将JSON的null值转换为空字符串

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

how to Flatten json null to empty string in golang

问题

我正在寻找一个用于将null JSON值转换为空字符串("")的Go库或解决方案,从

  1. {
  2. "foo": {
  3. "jim": null
  4. }
  5. }

转换为

  1. map[foo.jim:""]

目前,它在我的用例中被忽略了。有人可以帮我吗?

示例代码:https://go.dev/play/p/9hnMEa6QA2O
你可以看到我得到的输出是

  1. map[fee:bar]

但我想要的是

  1. map[foo.jim:"" fee:bar]
英文:

I am searching for go library or work around to flatten the null json value to empty string (""),
from

  1. `{
  2. "foo": {
  3. "jim":null
  4. }
  5. }`

to

  1. map[foo.jim:""]

as of now its being ignored for my use case.
can anybody help me with this.

example code https://go.dev/play/p/9hnMEa6QA2O
you can see that i get the output

  1. map[fee:bar]

but i want

  1. map[foo.jim:"" fee:bar]

答案1

得分: 0

在查看代码后,需要在switch语句中检查nil而不是忽略它。

  1. default:
  2. if v == nil {
  3. flatMap[newKey] = ""
  4. } else {
  5. flatMap[newKey] = fmt.Sprintf("%v", v)
  6. }
英文:

after going through the code,
had to check for nil instead of ignoring it in switch case.

  1. default:
  2. if v == nil {
  3. flatMap[newKey] = ""
  4. } else {
  5. flatMap[newKey] = fmt.Sprintf("%v", v)
  6. }

huangapple
  • 本文由 发表于 2022年6月24日 14:48:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/72739991.html
匿名

发表评论

匿名网友

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

确定