Go text/template模板:当JSON输入中的父节点不存在时,如何构建回退?

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

Go text/template templates: how to build a fallback when parent node in JSON input doesn't exist?

问题

假设你有一个通常会传入系统的 JSON 输入,例如:

{ "foods": { "plants": { "fruit": "apple" } } }

但是你希望能够处理一种情况,即 "plants" 节点不存在或其值为 null。例如:

{ "foods": { "plants": null } }

或者

{ "foods": { "fungi": { "mushrooms": "button" } } }

当我尝试使用各种 if 语句和其他方法(例如 {{ if .foods.plants.fruits }}stuff...{{ end }})时,我一直遇到错误,如 <.foods.plants.fruits>: map has no entry for key "plants"<.foods.plants.fruits>: nil pointer evaluating interface {}.fruits

我想要一个模板,在父节点不存在时,我可以尝试检查备选选项,而不会导致 Go 进入恐慌状态或模板拒绝继续执行。比如说,如果 "plants" 父节点不存在,可以使用 foods.fungi.mushrooms 作为替代节点。

在 Go 的文本模板中是否有可能实现这一点?我查阅了文档并进行了一些搜索,但没有找到明显的解决方案。

谢谢!

英文:

Let's say you have a JSON input that normally comes into your system, like:

{ "foods": { "plants": { "fruit": "apple" } } }

But you want to be able to handle a case where the "plants" node doesn't exist or its value is null. Like:

{ "foods": { "plants": null } }

or

{ "foods": { "fungi": { "mushrooms": "button" } } }.

When I've tried doing various if statements and things (like {{ if .foods.plants.fruits }}stuff...{{ end }}, I keep running into errors like <.foods.plants.fruits>: map has no entry for key "plants" or <.foods.plants.fruits>: nil pointer evaluating interface {}.fruits

I want a template where, if the parent node does not exist, I can try checking a fallback option, without the Go panicking or the template refusing to continue executing. Like, say, have it use foods.fungi.mushrooms alternate node if the plants parent node doesn't exist.

Is this possible in Go text/templates? I scoured through the docs and did some googling but am not seeing anything obvious.

Thanks!

答案1

得分: 1

一个同事给我提出了一个解决方案,最终起作用了:使用内置的 index 函数:

{{ if index .foods "plants" }}做一些事情{{ else }}当 '.foods.plants' 不存在时做其他事情{{ end }}

英文:

A coworker of mine suggested a solution that ended up working: use the built-in index function:

{{ if index .foods "plants" }}do stuff{{ else }}do other stuff when '.foods.plants' is missing{{ end }}

huangapple
  • 本文由 发表于 2022年7月26日 07:50:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/73116406.html
匿名

发表评论

匿名网友

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

确定