Praveen Praveen - 1 month ago 14
YAML Question

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.

The Output when I run the code:
yamlConfig.each{ k, v -> println "${k}:${v}" }
is:

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:

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


However, I am getting the value:
[XYZ]
. Instead I need the result as
XYZ
, without square brackets.

Yml file I am using:

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

Answer

This is because of the - character placed before your name property. It makes the yaml parser treat what's inside the services section as an array.

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.

So either remove the - or use yamlConfig['services'][0]['name'].