使用Groovy比较并替换JSON中的字符串[duplicate]

问题描述 投票:0回答:1

这个问题在这里已有答案:

我想知道如何将JSON中的字符串替换为另一个JSON。

 def old = '{"name" : "abc", "value": "123", "field" : "xyz"}'
 def neww = '{"name" : "abc", "value": "345" ,"field" : "xyz"}'

 def old_1 = new JsonSlurper().parseText(old)
 def neww_1 = new JsonSlurper().parseText(neww)

 def commons_slurp = old_1.intersect(neww_1)
 def difference_slurp = old_1.plus(neww_1)
 def final_slurp = difference_slurp.minus(commons_slurp)
 def replace_slurp = old.replace(final_slurp)

 print '\n' +  replace_slurp

最终的输出是{"name" : "abc", "345": "123", "field" : "xyz"}

我希望用新值替换旧值。

AND,我需要输出为{"name" : "abc", "value": "345", "field" : "xyz"}

json string groovy substring string-comparison
1个回答
1
投票

它更容易:

println groovy.json.JsonOutput.toJson(old_1+neww_1)    
© www.soinside.com 2019 - 2024. All rights reserved.