使用Groovy替换JSON嵌套字段campaign的Null值
使用Groovy替换JSON数组中campaign字段的Null值为指定结构对象
你可以通过Groovy的JsonSlurper和JsonBuilder工具轻松实现需求,以下是完整可运行的代码:
@Grab('org.codehaus.groovy:groovy-json:3.0.17') import groovy.json.JsonSlurper import groovy.json.JsonBuilder // 输入的合法JSON数组(原输入需包裹为数组格式以符合JSON规范) def inputJson = '''[ {"id":1,"campaign":{"id":10,"cost":0,"name":"Test"},"type":1,"typeName":"Email"}, {"id":2,"campaign":null,"type":2,"typeName":"File"}, {"id":3,"campaign":{"id":20,"cost":0,"name":"Test2"},"type":20,"typeName":"Visit"} ]''' // 解析JSON为Groovy可直接操作的对象集合 def jsonData = new JsonSlurper().parseText(inputJson) // 遍历处理每个元素:替换null的campaign为指定结构 jsonData.each { entry -> if (entry.campaign == null) { entry.campaign = [ id: null, cost: null, name: null ] } } // 生成格式化后的输出JSON def outputJson = new JsonBuilder(jsonData).toPrettyString() println(outputJson)
代码说明:
@Grab注解会自动拉取Groovy JSON处理依赖,适合脚本运行场景JsonSlurper将JSON字符串解析为Groovy的List和Map,可直接通过属性名操作字段- 遍历数组对象,判断
campaign是否为null,若是则替换为包含id、cost、name且值均为null的映射 JsonBuilder将处理后的Groovy对象转回JSON字符串,toPrettyString()生成可读性更强的格式化输出,若需紧凑格式可改用toString()
运行后输出:
[ { "id": 1, "campaign": { "id": 10, "cost": 0, "name": "Test" }, "type": 1, "typeName": "Email" }, { "id": 2, "campaign": { "id": null, "cost": null, "name": null }, "type": 2, "typeName": "File" }, { "id": 3, "campaign": { "id": 20, "cost": 0, "name": "Test2" }, "type": 20, "typeName": "Visit" } ]
内容的提问来源于stack exchange,提问作者sabyasachi
相关产品推荐
相关产品推荐

