Manu Q
Manu Q

Reputation: 25

yaml to json with Groovy

I have a yaml file on a Jenkins pipeline (scripted in Groovy) and I want to convert that yaml file to JSON format to be parsed in that format.

I defined a variable (data) that will contain all the yaml file content. Don't know if that makes it easier to convert or not, but otherwise I can just convert the yaml file without putting the content on a variable.

Groovy stage script:

stage ("GET deployConfig file"){
    def data = readYaml file: './evaluations/integration-test- 
    docker/dev/deployConfig.yaml'
    println("YAML-FILE: " + data)     
}

Does anyone know how can achieve that?

thanks

Upvotes: 2

Views: 7794

Answers (2)

Utsav
Utsav

Reputation: 404

Just in case someone finds this useful.

Using new JsonBuilder resulted in Jenkins (via a groovy script) throwing an exception; used JsonOutput.toJson(data) instead.

def json = JsonOutput.toJson(data)

Upvotes: 1

daggett
daggett

Reputation: 28564

Convert to json and write it to file

import groovy.json.*

stage{
    def data = readYaml file: ....
    def json = new JsonBuilder(data).toPrettyString()
    writeFile file: ..., text: json
}

Upvotes: 4

Related Questions