groovy加载YAML文件修改并将其写入文件中 [英] groovy load YAML file modify and write it in a file
问题描述
我有YMAL文件,使用groovy我想读取和修改一个元素值,然后将其写入另一个文件。
使用此代码,尝试修改从TopClass.py到changeclass.py的第一个文件值。
$ b
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 =
日期:2001-11-23 15:03:17 -5
用户:ed
致命:
未知变量bar
堆栈:
- file:TopClass.py
line:23
code:|
x = MoreObject(345 \\\\
)
- file:MoreClass.py
line:58
code:| -
foo = bar
是否有示例groovy代码来读取YAML文件并修改并将其写入文件?
感谢
SR
你的代码存在的问题是你试图访问 Map.Entry
object 'file'
作为List。这里yaml数据中的'Stack'
元素是一个包含两个地图的列表。因此,修改该值的正确方法是:
map.Stack [0] .file ='changeclass.py'
要将更改数据保存回文件,请使用 dump() code>方法。例如:
DumperOptions options = new DumperOptions()
options.setPrettyFlow(true)
options。 setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK)
yaml = new Yaml(options)
yaml.dump(map,new FileWriter(< filePath>))
您的情况下的输出为:
2001-11-23T20:03:17Z
用户:ed
致命:未知变量bar
堆栈:
- 文件:changeclass.py
行:23
代码:|
x = MoreObject(345 \\\
)
- file:MoreClass.py
line:58
code:foo = bar
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
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
这篇关于groovy加载YAML文件修改并将其写入文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!