简体   繁体   中英

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.

If productName with a value of test exists in the Yaml file, I want to update its respective URL productUrl with a new value.

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 .

  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"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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