简体   繁体   English

Groovy替换JSON Block中的字符串

[英]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) 我已经构建了此字符串(请注意,此字符串是可变的,但如下所示,并且对于“ Id1”或“ Id2”必须具有相同的语法,但值可以不同)

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 我喜欢将myList:[{“ Id”:0}]的整个值替换为str1,如下所示在我的JSON块中

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 我在该JSON块上得到的输出是这个,我不希望\\我尝试了转义,但是它不起作用

"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. 看来Groovy在我的“我不想要groovy做到这一点。”之后添加了这些\\。我希望它接受我的str1并将其替换到mylist中。我什至尝试在str1的“之后”添加\\或\\\\但它没有用。

I think I have to convert str1 to a map in groovy?? 我想我必须将str1转换为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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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