0

I am using a Groovy script to download and process list of json objects, ex.:

[{"id":"5e98ad599c8f","type":"sale"}, {"id":"dsfugjb8f","type":"return"}]

I use JsonSlurper and successfully iterate through the list entries and extract the individual key values in each iteration.
Problem is I also need to extract each list entry in its entirety as a string to store it in a variable. I used "it.toString() " which provides the entire entry, but without quotes around the keys and string values. I need to preserve the original format so that I can later use it as a valid Json string in some downstream process.

Here is the code

        groovy.json.JsonSlurper slurper = new groovy.json.JsonSlurper()
        def trans_list = slurper.parseText(trans_data)
        line_num = 0
        if ( trans_list[0] != null ) {  
            trans_list.each {it ->
                line_num++
                trans_rec.value['trans_json'] = it.toString()
                trans_rec.value['id'] = it.get('id')
                trans_rec.value['type'] = it.get('type')     
            }
        }

The result of saving a list entry for the example given above using it.toString() is:

   {id:5e98ad599c8f,type:sale}

Is there a way to extract the original json string for each entry?

Would appreciate help,

Fer

FZF
  • 855
  • 4
  • 12
  • 29
  • Does this answer your question? [Generate JSON object in Groovy](https://stackoverflow.com/questions/61905210/generate-json-object-in-groovy) – cfrick Feb 04 '21 at 06:32
  • @cfrick, no it would not. The input is already in Json format with quotes and {} and all. Problem seems to be that the JsonSlurper parser has removed all the quotes, not just around the keys, but around the string values as well. Is there a way to preserve the original content, yet be able to iterate through the list and extract key/value pairs too. I don't have to use JsonSlurper if there is another way that provides ability to iterate through the list, extract the key/values, as well as grabing the entire entry as was originally formatted. – FZF Feb 04 '21 at 17:22
  • 1
    Please use JsonOutput.toJson as stated in the above link. toString on a map is not suited for serializing data. – cfrick Feb 04 '21 at 18:05
  • Thank you @cfrick. Your solution worked. – FZF Feb 05 '21 at 23:27

0 Answers0