简体   繁体   中英

Groovy replacing a string in JSON Block

I have spent hours on this and getting frustrated now. I have built this string (note this string is variable but looks like below and must have the same syntax for "Id1" or "Id2" except the values can be different)

str1= [{"Id1": 775},{"Id2": 776}]

I like to replace the entire value for myList: [{"Id": 0}], as shown below in my JSON block with that str1

someJson: {
    "myList": [{"Id": 0}],
}

SO I have

abc = new groovy.json.JsonSlurper().parse(someJson);
abc.myList= str1

My resulting output on that JSON block is this, I dont want the \\ I have tried escaping but it doesnt work

"myList": "[{\"Id1\": 775},{\"Id2\": 776}]",

It looks like Groovy adds those \\ right behind my " I dont want groovy to do that. I want it to take my str1 and just replace it in mylist. I even tried adding \\ or \\\\ behind the " in str1 but it didnt work.

I think I have to convert str1 to a map in groovy?? so I tried

    abc.myList= Eval.me(str1)

but I am getting this error

Script1.groovy: 1: expecting '}', found ':' @ line 1, column 15.
   [{"Id1": 775},{"Id2": 776}]

I figured it ut at last

I have to create a list, then I have to iterate through the map items

def map = [:]
def list = []

iterate

map.clear()
map.put(Id,val);
list.add(map);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM