简体   繁体   English

使用 Groovy 更新 Yaml

[英]Updating Yaml using Groovy

I have the following Yaml file that I am trying to update, depending on whether a value for a particular key exits.我尝试更新以下 Yaml 文件,具体取决于是否存在特定键的值。

If productName with a value of test exists in the Yaml file, I want to update its respective URL productUrl with a new value.如果productName文件中存在值为test的 productName,我想用新值更新其各自的 URL productUrl

If I have a new productName called test that does not exist in the Yaml file, I want to be able to add a new entry to the Yaml file for this productName and its productUrl .如果我有一个名为test的新productName ,它在 Yaml 文件中不存在,我希望能够在 Yaml 文件中为此productName及其productUrl添加一个新条目。

  products:
    - productName: abc
      productUrl: https://company/product-abc
    - productName: def
      productUrl: https://company/product-def
    - productName: ghi
      productUrl: https://company/product-ghi
    - productName: jkl
      productUrl: https://company/product-jkl
    - productName: mno
      productUrl: https://company/product-mno
    - productName: pqr
      productUrl: https://company/product-pqr

This is what I have so far but I'm not sure if this can be re-written in a much cleaner way, or if there's a bug in my approach.这是我到目前为止所拥有的,但我不确定这是否可以以更干净的方式重写,或者我的方法中是否存在错误。

@Grab('org.yaml:snakeyaml:1.17')
import org.yaml.snakeyaml.Yaml

Yaml parser = new Yaml()
def p = parser.load(("company.yml" as File).text)
Boolean isProductNew = true

p.company.products.each { i ->
  if (i.productName == 'test') {
    i.productUrl = 'https://company/product-new-test'
    isProductNew = false
  }
}

if (isProductNew) {
  p.company.products << ["productName": "test", "productUrl": "https://company/product-test"]
}
println p

You can put the code in a cleaner way:您可以以更简洁的方式放置代码:

if( !p.company.products.any{ it.productName == 'test' } ) 
  p.company.products << [ productName: "test", productUrl: "https://company/product-test"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM