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

具有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{}.

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

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题