You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Helm实操问题:如何将点记法字符串转换为字典结构

问题:将点记法字符串转换为嵌套字典结构(Helm模板场景)

需要把形如topkey.nestedkey.morenestedkey的点记法字符串转换为嵌套字典结构:

topkey:
  nestedkey:
    morenestedkey: val1

输入的values.yaml格式如下:

custom:
 - name: topkey.nestedkey.morenestedkey
   value: val1
 - name: topkey2.nestedkey2.morenestedkey2
   value: val2

尝试过用Helm模板的set函数,但不知道如何处理嵌套键的存在性检查和逐层构建:

{{- range $item := .Values.custom }}
???
{{ $_ := set ?? ?? $item.value }}
{{- end }}

需求背景:custom数组由GUI生成,仅暴露常用配置项,同时允许用户添加额外自定义配置。


解决方案

可以通过拆分点记法键、逐层遍历构建嵌套结构的方式实现,结合Helm的split、lookup和set函数完成:

{{- $result := dict -}}
{{- range $item := .Values.custom -}}
  {{- $keys := splitList "." $item.name -}}
  {{- $current := $result -}}
  {{- range $index, $key := $keys -}}
    {{- if eq (add $index 1) (len $keys) -}}
      {{- $_ := set $current $key $item.value -}}
    {{- else -}}
      {{- $next := lookup $current $key -}}
      {{- if not $next -}}
        {{- $next = dict -}}
        {{- $_ := set $current $key $next -}}
      {{- end -}}
      {{- $current = $next -}}
    {{- end -}}
  {{- end -}}
{{- end -}}

# 输出最终的嵌套结构
{{- toYaml $result -}}

代码说明:

  1. 初始化空字典$result存储最终嵌套结构
  2. 遍历custom数组的每个配置项:
    • 用splitList "."将点记法的name拆分为键数组$keys
    • 用$current跟踪当前层级的字典
    • 遍历键数组:
      • 若为最后一个键,直接用set将value赋值给当前层级的该键
      • 若为中间键,先检查当前层级是否存在对应子字典:不存在则创建空字典并绑定到当前层级,再将$current切换到下一层级字典
  3. 最后通过toYaml将$result转为YAML格式输出

内容的提问来源于stack exchange,提问作者Stavros Kois

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 02:01:18