douhe5092 2018-05-22 07:24
浏览 202
已采纳

具有JSON嵌套属性的Golang YAML

I'm trying to parse some YAML from a file and convert each item to a flat JSON object.

I'm having some issues with datasets where there are multiple / nested objects.

  • I'm failing to unmarshal multiple items per file.
  • I'm unsure how to get nested properties such has item -> description -> en

When I run the following code I get the error.

cannot unmarshal !!map into []item.Item

I think I've got to look into sub-types within my structure, but I can't seem to get anything to work.

Any help would be appreciated.


Code:

import (
"gopkg.in/yaml.v2"
"io/ioutil"
)

func parseItemYaml() {
    filePath := "./typeIDs.yaml"

    yamlFile, err := ioutil.ReadFile(filePath)
    if err != nil {
        log.Printf("yamlFile.Get err #%v ", err)
    }

    itemData := map[int][]Item{}

    err = yaml.Unmarshal(yamlFile, &itemData)
    if err != nil {
        panic(err)
    }

    // Then convert to JSON
    // Eventual persistance
}

Item Structure:

type Item struct {
    ID            int
    Name          string  `yaml:"name"`
    Description   string  `yaml:"description"`
    GroupID       int     `yaml:"groupID"`
    IconID        int     `yaml:"iconID"`
    GraphicID     int     `yaml:"graphicID"`
    MarketGroupID int     `yaml:"marketGroupID"`
    Mass          float64 `yaml:"mass"`
    Published     bool    `yaml:"published"`
    Volume        float64 `yaml:"volume"`
}

Desired JSON format:

{
    "ID":1563,
    "Description":"Radiates an omnidirectional pulse from the ship that causes EM damage to surrounding vessels.",
    "GroupID":72,
    "IconID":112,
    "GraphicID":72,
    "MarketGroupID":382,
    "Mass":10.0,
    "Published":true,
    "Volume":12.5
},
{...},
{...}

Data Subset:

1563:
    description:
        de: Ein ungerichteter Rundum-Impuls der vom Schiff ausgestrahlt wird und bei
            umliegenden Schiffen EM-Schaden verursacht.
        en: Radiates an omnidirectional pulse from the ship that causes EM damage
            to surrounding vessels.
        fr: Émet une impulsion omnidirectionelle qui part du vaisseau et provoque
            des dégâts électromagnétiques à tous les vaisseaux situés à proximité.
        ja: 全方位にパルスを放射し、周囲の艦にEMダメージを与える。
        ru: Испускает сильный всенаправленный импульс, наносящий электромагнитный
            ущерб всем объектам, окружающим корабль.
        zh: 从舰船上发射一个全向脉冲,对周围船只造成电磁伤害。
    graphicID: 2032
    groupID: 72
    iconID: 112
    marketGroupID: 382
    mass: 10.0
    name:
        de: Small EMP Smartbomb I
        en: Small EMP Smartbomb I
        fr: Petite bombe de proximité à IEM I
        ja: 小型EMPスマートボムI
        ru: Small EMP Smartbomb I
        zh: 小型EMP立体炸弹 I
    portionSize: 1
    published: true
    radius: 1000.0
    volume: 12.5
1564:
    basePrice: 650000.0
    groupID: 152
    iconID: 112
    marketGroupID: 341
    name:
        de: Small EMP Smartbomb I Blueprint
        en: Small EMP Smartbomb I Blueprint
        fr: Plan de construction Petite bombe de proximité à IEM I
        ja: 小型EMPスマートボムIブループリント
        ru: Small EMP Smartbomb I Blueprint
        zh: 小型EMP立体炸弹蓝图 I
    portionSize: 1
    published: true
    volume: 0.01
1565:
    description:
        de: Ein ungerichteter Rundum-Impuls der vom Schiff ausgestrahlt wird und bei
            umliegenden Schiffen EM-Schaden verursacht.
        en: Radiates an omnidirectional pulse from the ship that causes EM damage
            to surrounding vessels.
        fr: Émet une impulsion omnidirectionelle qui part du vaisseau et provoque
            des dégâts électromagnétiques à tous les vaisseaux situés à proximité.
        ja: 全方位にパルスを放射し、周囲の艦にEMダメージを与える。
        ru: Испускает сильный всенаправленный импульс, наносящий электромагнитный
            ущерб всем объектам, окружающим корабль.
        zh: 从舰船上发射一个全向脉冲,对周围船只造成电磁伤害。
    graphicID: 2032
    groupID: 72
    iconID: 112
    marketGroupID: 382
    mass: 40.0
    name:
        de: Small EMP Smartbomb II
        en: Small EMP Smartbomb II
        fr: Petite bombe de proximité à IEM II
        ja: 小型EMPスマートボムII
        ru: Small EMP Smartbomb II
        zh: 小型EMP立体炸弹 II
    portionSize: 1
    published: true
    radius: 1000.0
    volume: 5.0
  • 写回答

1条回答 默认 最新

  • dqalnwuci494308 2018-05-22 08:14
    关注

    Make structs e.g. like this:

    type Language struct {
        De string `yaml:de`
        En string `yaml:en`
        Fr string `yaml:fr`
        Ja string `yaml:ja`
        Ru string `yaml:ru`
        Zh string `yaml:zh`
    }
    
    type Item struct {
        Description   Language `yaml:description`
        GroupID       int      `yaml:"groupID"`
        IconID        int      `yaml:"iconID"`
        GraphicID     int      `yaml:"graphicID"`
        MarketGroupID int      `yaml:"marketGroupID"`
        Mass          float64  `yaml:"mass"`
        Name          Language `yaml:name`
        Published     bool     `yaml:"published"`
        Volume        float64  `yaml:"volume"`
    }
    

    Also, as far as I see, it should be map[int]Item{} and not map[int][]Item{}.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 画CAD几张图片内容如下1111111111111111111111111111111111111111111
  • ¥15 基于python的电影系统推荐
  • ¥20 springmvc重定向和返回json
  • ¥15 数学建模——参会安排怎么做
  • ¥15 电脑键盘实现触摸功能
  • ¥25 matlab无法将表达式转换为双数组怎么解决?
  • ¥15 单片机汇编语言相关程序
  • ¥20 家用射频美容仪技术规格
  • ¥15 大家帮我看看为什么错了
  • ¥15 unity互动琴弦抖动效果