Praveen Praveen - 1 year ago 96
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}" }

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:
. Instead I need the result as
, without square brackets.

Yml file I am using:

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

Answer Source

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'].

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download