简体   繁体   English

无法从 groovy 中的 yml 文件中获取值

[英]Not able to get a value from yml file in groovy

I have stored an entire yaml file into a Map yamlConfig which i am able to print and check.我已将整个 yaml 文件存储到我可以打印和检查的Map yamlConfig中。

The Output when I run the code: yamlConfig.each{ k, v -> println "${k}:${v}" } is:运行代码时的输出: yamlConfig.each{ k, v -> println "${k}:${v}" }是:

Host:localhost
Port:10000
application:[name:ABC, preferences:[UUID:d3f3278e, server:localhost:2222]]
services:[[name:XYZ, instances:1, start:true]]
dataSets:[[name:ABC], [name:XYZ]]

Now, I am trying to fetch a value from Map using following code:现在,我正在尝试使用以下代码从 Map 中获取一个值:

println yamlConfig.get("services").getAt("name")

However, I am getting the value: [XYZ] .但是,我得到了值: [XYZ] Instead I need the result as XYZ , without square brackets.相反,我需要结果为XYZ ,没有方括号。

Yml file I am using:我正在使用的 Yml 文件:

Host: localhost
Port: 10000
application:
  name: ABC
  preferences:
    UUID: d3f3278e
    server: localhost:2222
services:
  - name: XYZ
    instances: 1
    start: true
data:
  - name: ABC
  - name: XYZ

This is because of the - character placed before your name property.这是因为-字符放置在您的name属性之前。 It makes the yaml parser treat what's inside the services section as an array.它使 yaml 解析器将services部分中的内容视为数组。

When you ask for the name property doing yamlConfig['services']['name'] groovy gives you all the macthing properties of array items in the services array, and it can only return them in another array.当您要求name属性时, yamlConfig['services']['name'] groovy 会为您提供 services 数组中数组项的所有 macthing 属性,并且它只能在另一个数组中返回它们。

So either remove the - or use yamlConfig['services'][0]['name'] .因此,要么删除-要么使用yamlConfig['services'][0]['name']

yamlConfig.get("services")

return a list but not a service, therefore when you apply getAt to the returned list of services it returns a list of names.返回一个列表而不是一个服务,因此当您将 getAt 应用于返回的服务列表时,它返回一个名称列表。

yamlConfig.get("services").getAt('name')

actually does实际上是

yaml['services'].collect { it['name'] }

so in order to get a name of a certain service you need to do something like this:因此,为了获得某个服务的名称,您需要执行以下操作:

println yaml['services'][0]['name']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM