arrays - 使用 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;
解决方案
你命名的变量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"
列表,使用循环可能更安全,特别是如果其中的元素数量可能因客户而异。
推荐阅读
- testing - 与 Gigya SSO 的 TestCafe 相关的问题
- spring - Jetty 9 出于安全原因不想显示 Stacktraces
- python - 在 Python 中将数据框转换为字典
- java - 字符串数组的 Filer 内容 (Java)
- json - Flutter中解析Json列表
- redis - 在命令行中使用 redis 变量(时间)
- kubernetes - github 操作 GKE 工作流 - 部署说明
- python - 用 pytest 模拟 Tornado parse_command_line
- javascript - 调整画布大小但大小固定(不改变大小)
- python - gekko 错误:矩阵在结构上是奇异的。怎么解决呢?