提问人:wolpurgisnacht 提问时间:9/26/2023 更新时间:9/27/2023 访问量:35
将 YAML 文件转换为 Groovy 地图结果,snakeyaml 以不需要的格式返回
Converting YAML file to Groovy map results with snakeyaml returns in undesirable format
问:
我正在尝试在 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']
答:
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
搜索部分正是我所缺少的。感谢您提供示例和资源。
评论
yamlMap['maintainers'][0]['component']
应该返回PowerPuff Girls
yamlMap.maintainers[0].component
ideal world
yamlMap.maintainers.each{i-> println groovy.json.JsonOutput.toJson(i) }
yamlMap.containsValue('PowerPuff Girls')
indexOf()
.toString()