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

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

how to Flatten json null to empty string in golang

问题

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

{
    "foo": {
        "jim": null
    }
}  

转换为

map[foo.jim:""]  

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

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

map[fee:bar]  

但我想要的是

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

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

`{
	"foo": {
			"jim":null
	}
}`  

to

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

map[fee:bar]  

but i want

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

答案1

得分: 0

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

default:
    if v == nil {
        flatMap[newKey] = ""
    } else {
        flatMap[newKey] = fmt.Sprintf("%v", v)
    }
英文:

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

default:
		if v == nil {
			flatMap[newKey] = ""
		} else {
            flatMap[newKey] = fmt.Sprintf("%v", v)
        }

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:

确定