You need to enable JavaScript to run this app. Go语言如何Unmarshal复杂嵌套YAML并提取Name、Version等字段
优惠活动
大模型
产品
解决方案
定价
更多

Go语言如何Unmarshal复杂嵌套YAML并提取Name、Version等字段

问题修复方案

你代码存在两处核心错误,同时缺少需要提取的目标字段定义,调整如下:

错误点说明

  • 标签不匹配:Index结构体的Entry字段对应的YAML键是entries,你写的yaml:"entry"拼写错误,导致无法映射到YAML中的对应数据,因此返回空map。
  • 标签重复:Entry结构体的Description字段错误使用了yaml:"created"标签,和Created字段标签重复,会出现值覆盖的问题。
  • 字段缺失:需要提取的Name、Version等字段没有在Entry结构体中定义,无法解析对应值。

修正后完整代码

package main

import (
    "fmt"
    "log"

    "gopkg.in/yaml.v2"
)

const index_yaml = `apiVersion: v1
entries:
    alpine:
    - created: 2016-10-06T16:23:20.499814565-06:00
        description: Deploy a basic Alpine Linux pod
        digest: 99c76e403d752c84ead610644d4b1c2f2b453a74b921f422b9dcb8a7c8b559cd
        home: https://helm.sh/helm
        name: alpine
        sources:
        - https://github.com/helm/helm
        urls:
        - https://technosophos.github.io/tscharts/alpine-0.2.0.tgz
        version: 0.2.0
    - created: 2016-10-06T16:23:20.499543808-06:00
        description: Deploy a basic Alpine Linux pod
        digest: 515c58e5f79d8b2913a10cb400ebb6fa9c77fe813287afbacf1a0b897cd78727
        home: https://helm.sh/helm
        name: alpine
        sources:
        - https://github.com/helm/helm
        urls:
        - https://technosophos.github.io/tscharts/alpine-0.1.0.tgz
        version: 0.1.0
    nginx:
    - created: 2016-10-06T16:23:20.499543808-06:00
        description: Create a basic nginx HTTP server
        digest: aaff4545f79d8b2913a10cb400ebb6fa9c77fe813287afbacf1a0b897cdffffff
        home: https://helm.sh/helm
        name: nginx
        sources:
        - https://github.com/helm/charts
        urls:
        - https://technosophos.github.io/tscharts/nginx-1.1.0.tgz
        version: 1.1.0
generated: 2016-10-06T16:23:20.499029981-06:00`

type Entry struct {
    Created     string `yaml:"created"`
    Description string `yaml:"description"`
    Home        string `yaml:"home"`
    Name        string `yaml:"name"`
    Version     string `yaml:"version"`
}

type Entries map[string][]Entry

type Index struct {
    ApiVersion string  `yaml:"apiVersion"`
    Entry      Entries `yaml:"entries"`
    Generated  string  `yaml:"generated"`
}

func main() {
    var index Index
    err := yaml.Unmarshal([]byte(index_yaml), &index)
    if err != nil {
        log.Fatal("解析错误", err)
        return
    }

    fmt.Printf("Index: %+v", index)
}

运行验证

修正后执行代码即可正常打印所有解析到的Entry数据,包含你需要的Name、Description、Version等字段。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 16:18:02