Jenkinsfile write JSON file

13,971

Solution 1

Got it!

script {
          def someMap = [
              'name' : "john",
              'surname' : "doe"
          ]
          def json = new groovy.json.JsonBuilder()
          json "people": someMap
          def file = new File("$WORKSPACE/people.json")
          file.write(groovy.json.JsonOutput.prettyPrint(json.toString()))
        }

Solution 2

You can use writeJSON: Write JSON to a file in the workspace.

https://jenkins.io/doc/pipeline/steps/pipeline-utility-steps/#writejson-write-json-to-a-file-in-the-workspace

Solution 3

If you don't want to use any plugin, there is a workaround with the core Jenkins method writeFile e.g.:

writeFile(
    file: "foo/bar.json",
    text: """\
        {
            'a': 'x',
            'b': 'y'
        }
    """.stripIndent()
)
Share:
13,971
JoP
Author by

JoP

Updated on June 21, 2022

Comments

  • JoP
    JoP almost 2 years

    From within my Jenkinsfile, I am trying to create and write a simple JSON file to the workspace folder.

    The contents of the JSON file should be:

    {"people": {"name":"john","surname":"doe"}}
    

    Any ideas?

  • JoP
    JoP over 5 years
    I've tried that and got the following error: java.lang.ClassCastException: org.jenkinsci.plugins.pipeline.utility.steps.json.WriteJSONS‌​tep.json expects interface net.sf.json.JSON but received class java.lang.String
  • Eugene Mihaylin
    Eugene Mihaylin over 5 years
    can not help you with java. i'll add java tag to question.
  • JoP
    JoP over 5 years
    I'm not using Java, but using plain old Groovy.
  • Eugene Mihaylin
    Eugene Mihaylin over 5 years
    java platform, i've added both tags
  • Matt Schuchard
    Matt Schuchard over 5 years
    @JoP It sounds like your usage of the method is wrong. Update your question?