将 YAML 文件转换为 Groovy 地图结果,snakeyaml 以不需要的格式返回

Converting YAML file to Groovy map results with snakeyaml returns in undesirable format

提问人:wolpurgisnacht 提问时间:9/26/2023 更新时间:9/27/2023 访问量:35

问:

我正在尝试在 Groovy 中使用 snakeyaml 解析 YAML 文件。目标是创建一张我最终可以从中搜索的地图。

我使用的文件结构如下:

maintainers:
  - component: PowerPuff Girls
    pg: Utonium Labs
    people:
      - Buttercup
      - Blossom
      - Bubbles
    files:
      - sugar/*
      - spice/*
      - things/*nice*
      - chemicalx/*
  - component: Gangreen Gang
    pg: Villians
    people:
      - Ace
      - Snake
      - Big Billy
    files:
      - ace/*
      - snake/*

问题是:当我创建一个映射并返回值时,该值偏离了我所希望的格式。此外,似乎没有一个 String 值被转换为 String。输出为:maintainers

[maintainers:[[component:PowerPuff Girls, pg:Utonium Labs, people:[Buttercup, Blossom, Bubbles], files:[sugar/*, spice/*, things/*nice*, chemicalx/*]], [component:Gangreen Gang, pg:Villians, people:[Ace, Snake, Big Billy], files:[ace/*, snake/*]]]]

在一个完美的世界里,我会:

[component: 'PowerPuff Girls', pg: 'Utonium Labs', people: ['Buttercup', 'Blossom', 'Bubbles'], files: ['sugar/*','spice/*','things/*nice*', 'chemicalx']], 
[component: 'Gangreen Gang', pg: 'Villians', people: ['Ace', 'Snake', 'Big Billy'], files: ['ace/*','snake/*']]

我一定错过了重新格式化这张地图的愚蠢之处。我欢迎所有建议!

第 1 步:将文件加载为 Map

Yaml yaml = new Yaml()
Map yamlMap = yaml.load(yamlFile)

第 2 步:将地图返回为观察格式 返回 yamlMap

结果:

[maintainers:[[component:PowerPuff Girls, pg:Utonium Labs, people:[Buttercup, Blossom, Bubbles], files:[sugar/*, spice/*, things/*nice*, chemicalx/*]], [component:Gangreen Gang, pg:Villians, people:[Ace, Snake, Big Billy], files:[ace/*, snake/*]]]]

我尝试分别定义单个键和值并重新构造它们,但它没有按预期拉取分组。例如:def myVariable = yamlMap['maintainers']['component']

时髦的 蛇yaml

评论

0赞 daggett 9/26/2023
yamlMap['maintainers'][0]['component']应该返回PowerPuff Girls
0赞 daggett 9/26/2023
相同但点符号yamlMap.maintainers[0].component
0赞 daggett 9/26/2023
可能最接近您的格式的是 JSON。ideal worldyamlMap.maintainers.each{i-> println groovy.json.JsonOutput.toJson(i) }
0赞 wolpurgisnacht 9/26/2023
谢谢大家。这有助于清理它,但我仍然有一个问题是将值作为字符串获取。例如,如果我使用它,它会失败,因为它不是地图转换中的字符串。话虽如此,既然我们在示例中使用了位置或整数,那么使用而不是搜索字符串和查找位置会更有意义吗?yamlMap.containsValue('PowerPuff Girls')indexOf()
0赞 cfrick 9/27/2023
我很难理解,你在追求什么。维护者持有地图列表,这就是你得到的。您是否正在为数据结构而苦苦挣扎?然后,您可以更改 YAML。或者你是在Groovy战斗?永远不应将其用作序列化格式。坚持使用 YAML 或 JSON。.toString()

答:

0赞 daggett 9/27/2023 #1

可能最接近您的格式的是 JSON。ideal world

yamlMap.maintainers.each{ i-> println groovy.json.JsonOutput.toJson(i) }

如果要搜索与某个值匹配的项目:component

println yamlMap.maintainers.find{i-> i.component=='Gangreen Gang' } // equals
println yamlMap.maintainers.find{i-> i.component=~'green' }         // regex match
println yamlMap.maintainers.findAll{i-> i.component=~'green' }      // find all
println yamlMap.maintainers.findIndexOf{i-> i.component=~'green' }  // return index instead of element

列表/集合中更多时髦的方法:

https://docs.groovy-lang.org/latest/html/groovy-jdk/java/util/List.html

评论

0赞 wolpurgisnacht 9/27/2023
搜索部分正是我所缺少的。感谢您提供示例和资源。