我有来自服务器的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;
答案 0 :(得分:0)
名为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"
是一个列表,所以使用循环可能会更安全,尤其是其中循环中的元素数量可以根据客户而有所不同时。