Groovy upload the YAML file, modify and write it to a file

I have YMAL files using groovy I want to read and change the value of one element and then write it to another file.

When playing with this code, you are trying to change the first value of the file from TopClass.py to changeclass.py. But this does not change the meaning.

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 any groovy code example for reading a YAML file and changing and writing it to a file?

Thanks SR

+2
source share
1 answer

The problem with your code is that you are trying to access the object Map.Entry 'file'as a list. Here the item 'Stack'in your yaml data is a list containing two Maps. So the correct way to change the value is:

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

, dump(). :

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

:

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
+2

Source: https://habr.com/ru/post/1673714/


All Articles