如何从 Groovy 脚本中的 JSON 检索所有键值对避免键重复

How to retrieve all key-value pairs avoiding key duplication from JSON in Groovy script

我完全不熟悉 groovy 脚本,希望得到一些帮助来解决这个问题。我有一个 JSON 响应,我想通过避免重复来操纵并取回所需的参数。 Json 响应没有像 0,1,2.. 这样的索引,我可以遍历它。

这是我想要处理的回复:

{
"AuthenticateV2" : {
  "displayName" : "Verification of authentication",
  "description" : "notification ",
  "smsTemplate" : "authentication.v2.0_sms",
  "emailHeaderTemplate" : "v2.0_header",
  "emailBodyTemplate" : "html",
  "parameters" : {
     "displayName" : "USER_DISPLAY_NAME",
     "actionTokenURL" : "VERIFICATION_LINK",
     "customToken" : "VERIFICATION_CODE"
  },
  "supportedPlans" : [
     "connectGo"
  ]
},
"PasswordRecovery" : {
  "displayName" : "Verification of password recovery",
  "description" : "notification",
  "smsTemplate" : "recovery.v1.0_sms",
  "emailHeaderTemplate" : "recovery.v1.0_header",
  "emailBodyTemplate" : "recovery.v1.0_body_html",
  "parameters" : {
     "displayName" : "USER_DISPLAY_NAME",
     "actionTokenURL" : "VERIFICATION_LINK",
     "customToken" : "VERIFICATION_CODE",
     "adminInitiated" : false,
     "authnId" : "AUTHENTICATION_IDENTIFIER",
     "authnType" : "EMAIL",
     "user" : {
        "displayName" : "USER_DISPLAY_NAME"
     }
  },
  "supportedPlans" : [
     "connectGo"
  ]
},
"PasswordReset" : {
  "displayName" : "password reset",
  "description" : "notification",
  "smsTemplate" : "recovery.v1.0_sms",
  "emailHeaderTemplate" : "recovery.v1.0_header",
  "emailBodyTemplate" : "html",
  "parameters" : {
     "displayName" : "USER_DISPLAY_NAME",
     "user" : {
        "displayName" : "USER_DISPLAY_NAME"
     }
  }

我想要的预期输出:

{
     "displayName" : "USER_DISPLAY_NAME",
     "actionTokenURL" : "VERIFICATION_LINK",
     "customToken" : "VERIFICATION_CODE",
     "customToken" : "VERIFICATION_CODE",
     "adminInitiated" : false,
     "authnId" : "AUTHENTICATION_IDENTIFIER",
     "authnType" : "EMAIL"
  }

我需要检索参数标签下的所有字段并且还想避免重复

您应该首先熟悉 parsing and producing JSON in Groovy

然后,假设提供的响应是有效的 JSON(它不是 - 最后缺少 2 个结束卷曲 (}))以获取所有 parameters 键合并为一个 JSON 我们必须首先使用 JsonSlurper:

将 JSON 字符串转换为 Map 对象
def validJsonResponse = '<your valid JSON string>'
Map parsedResponse = new JsonSlurper().parseText(validJsonResponse) as Map

现在,当我们有一个 parsedResponse 映射时,我们可以遍历响应中的所有根项,并使用 Map::collectEntries方法:

Map uniqueParameters = parsedResponse.collectEntries { it.value['parameters'] }

最后,我们可以使用 JsonOuput:

uniqueParameters 结果转换回漂亮的 JSON 字符串
println JsonOutput.prettyPrint(JsonOutput.toJson(uniqueParameters))

应用以上所有内容后,我们将得到输出

{
    "displayName": "USER_DISPLAY_NAME",
    "actionTokenURL": "VERIFICATION_LINK",
    "customToken": "VERIFICATION_CODE",
    "adminInitiated": false,
    "authnId": "AUTHENTICATION_IDENTIFIER",
    "authnType": "EMAIL",
    "user": {
        "displayName": "USER_DISPLAY_NAME"
    }
}

如果您想从最终输出中删除 user 条目,只需将其从生成的 uniqueParameters 映射 (uniqueParameters.remove('user')) 中删除,然后再将其转换回 JSON 字符串。