Search code examples
jenkinsgroovyjenkins-pipeline

Jenkins pipeline error in handling json file


I'm newbie to Jenkins pipeline and writing a groovy script to parse a json file. However I'm facing an error which many have faced but none of the solutions worked for me. Below is my Jenkinsfile and error msg.

def envname = readJSON file: '${env.WORKSPACE}/manifest.json'
pipeline {
    agent any
    stages { 
        stage('Build') {
            steps {
                echo WORKSPACE
                sh "ls -a ${WORKSPACE}"
            } 
        }
        }
 }

[Pipeline] Start of Pipeline [Pipeline] readJSON [Pipeline] End of Pipeline org.jenkinsci.plugins.workflow.steps.MissingContextVariableException: Required context class hudson.FilePath is missing Perhaps you forgot to surround the code with a step that provides this, such as: node at org.jenkinsci.plugins.pipeline.utility.steps.AbstractFileOrTextStepExecution.run(AbstractFileOrTextStepExecution.java:30)

I even tried readJSON file: '${WORKSPACE}/manifest.json but that didn't work too. I'm sure the mistake is with the first line since when removing that line, there execution is successful. The docs are pretty helpful but I'm not able to track down where exactly I'm going wrong that is why posted here.

UPDATE:

I tried the following methods def envname = readJSON file: "./manifest.json" and def envname = readJSON file: "${env.WORKSPACE}/manifest.json" and even tried them defining under the steps block. Nothing worked. Below is the error msg I recieved when I defined them under step block

WorkflowScript: 5: Expected a step @ line 7, column 13 def envname = ^

Below is the official syntax doc of readJson and I can see that I'm using the correct syntax only. but still doesn't work as expected. https://www.jenkins.io/doc/pipeline/steps/pipeline-utility-steps/#readjson-read-json-from-files-in-the-workspace


Solution

  • I've solved this myself with the help of "Matt Schuchard"'s below answer. I'm not sure whether this is the only way to solve but this worked for me.

    pipeline {
        agent any
        stages { 
            stage('Json-Build') {
                steps {
                    script {
                        def envname = readJSON file: "${env.WORKSPACE}/manifest.json"
                        element1 = "${envname.dev}"
                        echo element1
                    }
                } 
            }
            }
     }