Home > Mobile >  Jenkins read json file with multiple list value jsonsurper or readjson
Jenkins read json file with multiple list value jsonsurper or readjson

Time:08-22

I want to be able ro read json format based on parameter value selected in choice. e.g If dev is selected, it should select (dev1,dev2,dev3) and loop through each selected in json through the node. what is important now is to get the value in json to a file and then I call call it from file into the node

error:

groovy.lang.MissingMethodException: No signature of method: net.sf.json.JSONObject.$() is applicable for argument types: (org.jenkinsci.plugins.workflow.cps.CpsClosure2) values: [org.jenkinsci.plugins.workflow.cps.CpsClosure2@7e1eb88f]
Possible solutions: is(java.lang.Object), any(), get(java.lang.Object), get(java.lang.String), has(java.lang.String), opt(java.lang.String)

script in pipeline

    #!/usr/bin/env groovy     
node{
    properties([
    parameters([


   choice(
        name: 'environment',
        choices: ['','Dev', 'Stage', 'devdb','PreProd','Prod' ],
        description: 'environment to choose'
        ),

    ])
]) 

node () {
  def myJson = '''{
     "Dev": [
        "Dev1",
        "Dev2",
        "Dev3"
    ],
    "Stage": [
        "Stage1",
        "Stage2"
    ],
    "PreProd": [
        "Preprod1"
    ],
    "Prod": [
        "Prod1",
        "Prod2"
    ]

}''';
  def myObject = readJSON text: myJson;
  echo myObject.${params.environment};
  
// put the list of the node in a file or in a list to loop 
}

CodePudding user response:

Using Pipeline Utility Steps, it can be easier:

Reading from string:

def obj = readJSON text: myjson

Or reading from file:

def obj = readJSON file: 'myjsonfile.json'

Now you can get the element and iterate the list:

def list = obj[params.environment]

list.each { elem ->
  echo "Item: ${elem}"
}

Reference: https://www.jenkins.io/doc/pipeline/steps/pipeline-utility-steps/#readjson-read-json-from-files-in-the-workspace

CodePudding user response:

Let me make it simple. To read the json file you need to download it from git or wherever you stored it. Let's assume git in this case. Once the json file is downloaded then you want to access the content of json file in your code. Which can be done by this code.

import groovy.json.JsonSlurperClassic
def downloadConfigFile(gitProjectURL, jsonnFileBranch) {
   // Variables
   def defaultBranch = jsonnFileBranch
   def gitlabAdminCredentials = 'admin'
   def poll = false
   def jenkinsFilePath = 'jenkins.json'

   // Git checkout
   git branch: defaultBranch, credentialsId: gitlabAdminCredentials, poll: poll, url: gitProjectURL

   // Check if file existed or not
   def jenkinsFile = fileExists(jenkinsFilePath)
   if (jenkinsFile) {
      def jsonStream = readFile(jenkinsFilePath)
      JsonSlurperClassic slurper = new JsonSlurperClassic()
      def parsedJson = slurper.parseText(jsonStream)
      return parsedJson
   } else {
      return [:]
   }
}

Now we have the entire json file parsed using above function.

Now you can call the function and read the value in a global variable.

 stage('Download Config') {
               jsonConfigData = downloadConfigFile(gitProjectURL, jsonnFileBranch)
               if (jsonConfigData.isEmpty()) {
                  error err_jenkins_file_does_not_exists
               } else {
                  println("jsonConfigData : ${jsonConfigData}")
}

Now you can access the value of json file or say variable like this.

def projectName = jsonConfigData.containsKey('project_name') == true ? jsonConfigData['project_name'] : ''

You can access any thing if its child node in similar way. I hope it helps you.

  • Related