使用snakeyaml将YAML文件转换为GroovyMap结果,返回格式不合要求

lxkprmvk  于 7个月前  发布在  其他
关注(0)|答案(1)|浏览(54)

我试图在Groovy中使用snakeyaml解析一个YAML文件。我们的目标是创建一个Map,我最终可以搜索。
我使用的文件结构如下:

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/*

问题是:当我创建一个map并返回值时,maintainers的值与我所希望的格式不符。此外,似乎没有一个String值被转换为String。输出为:

[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/*']]

我一定是错过了一些愚蠢的重新格式化这张Map。欢迎所有建议!
步骤1:将文件加载为Map

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

步骤2:返回map以观察格式return 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']

bkhjykvo

bkhjykvo1#

最接近ideal world的可能是json。

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

列表/集合上的更多groovy方法:
https://docs.groovy-lang.org/latest/html/groovy-jdk/java/util/List.html

相关问题