-1

I am trying to correct the Incoming JSON as I have a JSON to XML converter. I wish to replace the leading number in a field etc 1Doc1 to S_Doc1 etc. Also I Need to replace the invalid XML element names from JSON such as Slash etc. Here is my Code but it is not working:

def list = new JsonSlurper().parseText( payload )

list.each {
  def oldStr = "" + it
  def newStr = oldStr.replaceFirst("^[^a-zA-Z]+", "S_")
  payload = payload.replaceFirst(oldStr, newStr)   
 }
 return payload

I get the Input as is. Could anyone advise how to do this in Groovy. For example if my Input is:

{
"1Document1":
{"Record":{"Header"...….

The Output should be

{
"S_Document1":
{"Record":{"Header"......
CodeMonkey
  • 22,825
  • 4
  • 35
  • 75
Tppi
  • 3
  • 5
  • If you have code, that "is not working", please add what is not working (e.g. errors, exceptions, logs, ...) toe the question or how the result differs. Also make sure to provide a minimal failing example. – cfrick Jan 24 '20 at 20:22
  • The Code I wrote prints the Input as is, with no modification at all – Tppi Jan 27 '20 at 08:57

1 Answers1

0

You can use eachWithIndex and update the element in the list using key instead of trying to manipulate the input string:

import groovy.json.JsonSlurper

String json = '[{"1Document1": {"Record":{"Header": "xx"}}}, {"2Document1": {"Record":{"Header": "zz"}}}]'

def list = new JsonSlurper().parseText( json )

list.eachWithIndex {v, k ->
    def newStr = (""+v).replaceFirst("^[^a-zA-Z]+", "S_")
    list[k] = newStr
 }

 println list
marekful
  • 14,986
  • 6
  • 37
  • 59
  • The Code seems fine, but infortunately JsonSlurper is creating list of a single item with the entire JSON payload. I am trying to debug it. – Tppi Jan 27 '20 at 11:08