<p>Following is the code that worked for me, if there is any other better way to do this, suggestions are most welcome.</p>
<p><strong>Main Method:</strong></p>
<pre><code>def transformjsonfile(propertiesPath, jsonfilepath) {

  // Load Properties file 
  Properties props = new Properties()
  props.load(new StringReader(readFile(propertiesPath)))

  // Load json file
  def json = jsonParseFile(jsonfilepath)

  // Transform json
  json = transformValues(props, json)
  
  // Write back the tranformed config to the json file
  formatAndWriteBackJson(json)
} 
</code></pre>
<p><strong>Helper methods:</strong></p>
<pre><code>def jsonParseFile(def jsonfilepath) {
    def fileContent = readFile(file: jsonfilepath, encoding: &quot;UTF-8&quot;)
    def jsonSlurper = new JsonSlurperClassic()
    def data = jsonSlurper.parseText(fileContent.replaceAll(&quot;\\s&quot;, &quot;&quot;).replaceAll(&quot;\uFEFF&quot;, &quot;&quot;))
    return data
}

def formatAndWriteBackJson(json)
{
  def jsonOut = new JsonBuilder(json).toPrettyString()
  writeFile file: jsonfilepath, text: jsonOut.toString()
}

def transformValues(props, json) {
  for (String name: props.keySet()) {
    String givenValue = props.getProperty(name);
    String value = givenValue.trim();
    if (name.startsWith(&quot;json_${env.Environment}_&quot;)) {
      splitarray = name.split(&quot;json_${env.Environment}_&quot;)
      jsonvalue = splitarray[1]
      key = &quot;${jsonvalue}&quot;
      transformvalue = &quot;${value}&quot;
      def someString = &quot;${key}&quot;
      def someChar = '.'
      int count = 0;
      for (int i = 0; i &lt; someString.length(); i++) {
        if (someString.charAt(i) == someChar) {
          count++;
        }
      }
      keyvalue = &quot;json&quot;
      splitarray = key.split('\\.')
      lab1: for (int j = 0; j &lt;= count; j++) {
        keyvalue = keyvalue + &quot;.&quot; + splitarray[j]
        jsonvalue = Eval.me('json', json, &quot;${keyvalue}&quot;)
        if (jsonvalue == null) {
          break lab1;
        }
        if (jsonvalue != null) {
          println 'condition met'
          if (j == count) {
            Eval.me('json', json, &quot;${keyvalue} ='$transformvalue'&quot;)
          }
        }
      }
    }
  }
  return json
}
</code></pre>

CC BY-SA 4.0
2022-05-02T09:14:27.410Z
2022-05-02T09:14:27.410Z
Sreehari
<p>I have a Jenkins job which runs on a slave node on another machine, both master and slave run on windows. The slave node is being run as a windows service. I am unable to read a json file from workspace in the slave node and parse it. The JSON file structure is like given below. I need to read the EmailProperties object and modify each of the properties and save the json file again. I have tried multiple suggestions on readFile() &amp; readJSON(), but none  of them is working. Any help on this would be highly appreciated.</p>
<p><strong>JSON file:</strong></p>
<pre><code>{
  &quot;Logging&quot;: {
    &quot;LogLevel&quot;: {
      &quot;Default&quot;: &quot;Information&quot;,
      &quot;Microsoft&quot;: &quot;Warning&quot;,
      &quot;Microsoft.Hosting.Lifetime&quot;: &quot;Information&quot;
    }
  },
  &quot;AllowedHosts&quot;: &quot;*&quot;,
  &quot;EmailProperties&quot;: {
      &quot;MailPort&quot;: &quot;587&quot;,
      &quot;MailServer&quot;: &quot;mydomainmailserver.outlook.com&quot;,
      &quot;Password&quot;: &quot;password123$&quot;,
      &quot;Sender&quot;: &quot;company@domain.com&quot;
    }
}
</code></pre>
<p><strong>Properties file:</strong></p>
<pre><code>[transformation]
json_dev_EmailProperties.MailPort = 663
json_dev_EmailProperties.MailServer = devmailserver.outlook.com
json_dev_EmailProperties.Password = DevPassword123$
json_dev_EmailProperties.Sender = company@devmailserver.outlook.com
</code></pre>

<jenkins-pipeline><pipeline><json>
Read and parse json file from workspace on slave node
Sreehari
# Read and parse json file from workspace on slave node

(Asked by: username_0 on 2022-04-29)

I have a Jenkins job which runs on a slave node on another machine, both master and slave run on windows. The slave node is being run as a windows service. I am unable to read a json file from workspace in the slave node and parse it. The JSON file structure is like given below. I need to read the EmailProperties object and modify each of the properties and save the json file again. I have tried multiple suggestions on readFile() & readJSON(), but none  of them is working. Any help on this would be highly appreciated.
JSON file:
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "EmailProperties": {
      "MailPort": "587",
      "MailServer": "mydomainmailserver.outlook.com",
      "Password": "password123$",
      "Sender": "company@domain.com"
    }
}

Properties file:
[transformation]
json_dev_EmailProperties.MailPort = 663
json_dev_EmailProperties.MailServer = devmailserver.outlook.com
json_dev_EmailProperties.Password = DevPassword123$
json_dev_EmailProperties.Sender = company@devmailserver.outlook.com

**Tags:** jenkins-pipeline, pipeline, json


---

## 1 answers

### Answer by username_0 on 2022-05-02. Score: 0 | Accepted answer

Following is the code that worked for me, if there is any other better way to do this, suggestions are most welcome.
Main Method:
def transformjsonfile(propertiesPath, jsonfilepath) {

  // Load Properties file 
  Properties props = new Properties()
  props.load(new StringReader(readFile(propertiesPath)))

  // Load json file
  def json = jsonParseFile(jsonfilepath)

  // Transform json
  json = transformValues(props, json)
  
  // Write back the tranformed config to the json file
  formatAndWriteBackJson(json)
} 

Helper methods:
def jsonParseFile(def jsonfilepath) {
    def fileContent = readFile(file: jsonfilepath, encoding: "UTF-8")
    def jsonSlurper = new JsonSlurperClassic()
    def data = jsonSlurper.parseText(fileContent.replaceAll("\\s", "").replaceAll("\uFEFF", ""))
    return data
}

def formatAndWriteBackJson(json)
{
  def jsonOut = new JsonBuilder(json).toPrettyString()
  writeFile file: jsonfilepath, text: jsonOut.toString()
}

def transformValues(props, json) {
  for (String name: props.keySet()) {
    String givenValue = props.getProperty(name);
    String value = givenValue.trim();
    if (name.startsWith("json_${env.Environment}_")) {
      splitarray = name.split("json_${env.Environment}_")
      jsonvalue = splitarray[1]
      key = "${jsonvalue}"
      transformvalue = "${value}"
      def someString = "${key}"
      def someChar = '.'
      int count = 0;
      for (int i = 0; i < someString.length(); i++) {
        if (someString.charAt(i) == someChar) {
          count++;
        }
      }
      keyvalue = "json"
      splitarray = key.split('\\.')
      lab1: for (int j = 0; j <= count; j++) {
        keyvalue = keyvalue + "." + splitarray[j]
        jsonvalue = Eval.me('json', json, "${keyvalue}")
        if (jsonvalue == null) {
          break lab1;
        }
        if (jsonvalue != null) {
          println 'condition met'
          if (j == count) {
            Eval.me('json', json, "${keyvalue} ='$transformvalue'")
          }
        }
      }
    }
  }
  return json
}


---

