Home > Mobile >  How to parse JSON file in Jenkinsfile and read the key value pair
How to parse JSON file in Jenkinsfile and read the key value pair

Time:01-08

I'm fairly new to Jenkins, Jenkinsfile and Groovy and not sure how to read a JSON file in Jenkinsfile. I read the article at: https://www.jenkins.io/doc/pipeline/steps/pipeline-utility-steps/#readjson-read-json-from-files-in-the-workspace. However, the article is not clear with its implementation. I tried following code, but it fails.

def jFile = readJSON file: 'file.json'
pipeline 
{
    //agent any
    agent 
    {
        // Some code
    }
    stages 
    {
        stage('Init') 
        { 
            steps 
            {
                echo jFile['context']
            }
        }
    }
}

Error:

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

Any suggestions?

CodePudding user response:

You need to read the file within a Step in the declarative Pipeline.

pipeline 
{
    //agent any
    agent 
    {
        // Some code
    }
    stages 
    {
        stage('Init') 
        { 
            steps 
            {
              script {
                def jFile = readJSON file: 'file.json'
                echo "${jFile['context']}"
               }
            }
        }
    }
}

  • Related