首页 > 解决方案 > 使用 Groovy 修改 JSON 键

问题描述

我有来自服务器的 JSON 输出,如下所示,我试图清理键值以减少它们的长度并删除它们的空格。我可以使用 put/remove 修复数组的初始键,但似乎无法对数组的键值执行相同的操作。

{
"Customer Information": [
     {"Data Table - F0102 [Contacts - Emails]": [{
     "name":"xxxxx",
     "email":"xxxxx"
     }]},
     {"Data Table - F3392 [Contacts - Phone Numbers]":[{
     "phone_desc":"xxxxx",
     "phone_number":"xxxxx"
     }]}
],
"address":"xxxxx",
"city":"xxxxx",
"state":"xxxxx",
"zip":"xxxxx"
}

我正在使用以下代码:

import groovy.json.JsonSlurper;
import groovy.json.JsonBuilder;

def jsonSlurper = new JsonSlurper();
def object = jsonSlurper.parseText'''{JSON FROM ABOVE}'''

// this first line works, and updates to customer_info
object.put("customer_info", object.remove("Customer Information"));

// this line seems to be ignored
object.put("email_info", object.remove("Data Table - F0102 [Contacts - Emails]"));

def jsonOut = new JsonBuilder(object).toPrettyString();
return jsonOut;

标签: arraysjsongroovy

解决方案


你命名的变量object有点伤害我的眼睛:-) 你可能想给它一个更具描述性的名字。同样,您可以删除;常规代码。

无论如何,“对象”是Map<String, Object>从根部描述您的 json 的。所以,object."Customer Information"存在但object."Data Table - F0102 [Contacts - Emails]"不存在。object."Customer Information"[0]."Data Table - F0102 [Contacts - Emails]"做。

所以你可以object.put("email_info", object.remove("Data Table - F0102 [Contacts - Emails]"))object.customer_info[0].put("email_info", object.customer_info[0].remove('Data Table - F0102 [Contacts - Emails]')). 但是作为object."Customer Information"列表,使用循环可能更安全,特别是如果其中的元素数量可能因客户而异。


推荐阅读