【问题标题】:Compare and replace string in JSON using Groovy [duplicate]使用 Groovy 比较和替换 JSON 中的字符串 [重复]
【发布时间】:2018-06-14 23:24:46
【问题描述】:

我想知道如何将 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"}

我想用新值替换旧值。

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

【问题讨论】:

  • 如果您对所述合并地图的输出感到困惑:JsonOutput.toJson(old_1+neww_1)

标签: json string groovy substring string-comparison


【解决方案1】:

这更容易:

println groovy.json.JsonOutput.toJson(old_1+neww_1)    

【讨论】:

  • 你说“两个输出”是什么意思?在常规 map1 + map2 == map1.plus(map2) 中。方法 .plus 返回一个新的 Map ,其中包含从左到右的所有条目,优先于右。
猜你喜欢
  • 2013-04-28
  • 1970-01-01
  • 2016-01-31
  • 2011-03-25
  • 2020-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多