Go模板 – 递归搜索所有键

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

Go templates - Search all keys recursively

问题

我经常发现自己需要在 docker x 命令的输出中查找特定的键。我通常使用 grep 或者有时使用 jq 命令,但是也许 go 模板有一些构建机制可以输出一个键及其值,而不需要知道该值的具体 "路径"。

例如,在 docker image inspect <x> 命令中,Cmd 的路径可能是 [0].ContainerConfig.Cmd 或者 [0].Config.Cmd

是否可以在 Go 模板中检索这两个键及其值?

英文:

I often find myself in need to find a specific key in docker x command output. I usually use grep sometimes jq command but maybe go templates have some build mechanism to output a key and it's value without knowing the specific "path" of that value ?

For example in case of docker image inspect <x> command the path to Cmd would be something like [0].ContainerConfig.Cmd or [0].Config.Cmd

is it possible to retrieve both of those keys and their values in Go template ?

答案1

得分: 2

只是笨拙地。将其拆分为多行,你可以这样写:

{{- if .ContainerConfig.Cmd -}}
{{- .ContainerConfig.Cmd -}}
{{- else if .Config.Cmd -}}
{{- .Config.Cmd -}}
{{- else -}}
""
{{- end -}}

你需要删除换行符并将其打包成单个 docker inspect -f 选项,这很不方便。

如你在问题中建议的那样使用 jq 可能会更容易一些;或者使用 Docker SDK,如 @Vorsprung 建议的,可以让你在比裸露的 Go text/template 语言更丰富的语言中以代码的形式完成这个任务。

英文:

Only awkwardly. Split on to multiple lines, you could write

{{- if .ContainerConfig.Cmd -}}
{{- .ContainerConfig.Cmd -}}
{{- else if .Config.Cmd -}}
{{- .Config.Cmd -}}
{{- else -}}
""
{{- end -}}

You'd have to remove the newlines and pack that into a single docker inspect -f option, which is inconvenient.

Using jq as you suggest in the question is probably a little easier; or @Vorsprung's suggestion of using a Docker SDK will let you do this in code in a language richer than the bare Go text/template language.

huangapple
  • 本文由 发表于 2021年12月6日 02:56:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/70237545.html
匿名

发表评论

匿名网友

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

确定