groovy load YAML file modify and write it in a file

sfgroups picture sfgroups · Jan 8, 2016 · Viewed 9.2k times · Source

I have YMAL files, using groovy I want to read and modify one element value, then write it into another file.

Playing with this code, trying to modify first filevalue from TopClass.py to changeclass.py. But its not modifying the value.

import org.yaml.snakeyaml.Yaml

class Test{
    def static main(args){
        Yaml yaml = new Yaml()
        def Map  map = (Map) yaml.load(data)
        println map.Stack.file[0]
        map.Stack.file[0]='changeclass.py'
        println map.Stack.file[0]
    }

def static String data="""
Date: 2001-11-23 15:03:17 -5
User: ed
Fatal:
  Unknown variable "bar"
Stack:
  - file: TopClass.py
    line: 23
    code: |
      x = MoreObject("345\\n")
  - file: MoreClass.py
    line: 58
    code: |-
      foo = bar
"""

Is there sample groovy code to read the YAML file and modify and write it into file?

Thanks SR

Answer

Sandeep Poonia picture Sandeep Poonia · Jan 8, 2016

The problem with your code is that you are trying to access a Map.Entry object 'file' as a List. Here the 'Stack' element in your yaml data is a list that contains two Maps. So the correct way to modify the value would be:

map.Stack[0].file = 'changeclass.py'

To save the changes data back to a file, use dump() method. for eg:

DumperOptions options = new DumperOptions()
options.setPrettyFlow(true)
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK)
yaml = new Yaml(options)
yaml.dump(map, new FileWriter(<filePath>))

Output in your case would be:

Date: 2001-11-23T20:03:17Z
User: ed
Fatal: Unknown variable "bar"
Stack:
- file: changeclass.py
  line: 23
  code: |
    x = MoreObject("345\n")
- file: MoreClass.py
  line: 58
  code: foo = bar