【问题标题】:How to remove key value pair from json using Dataweave in mule4如何在 mule4 中使用 Dataweave 从 json 中删除键值对
【发布时间】:2021-11-27 12:10:04
【问题描述】:

如果它为空,我想从 json 有效负载中删除一个键。

{
    "transactionDetails": {
        "maintenanceType": null,
        "transactionDate": "2021-10-07T05:38:38.44-05:00"
    },
    "account": {
        "agentOfRecord": {
            "type": "true",
            "rateType": ""

        },
        "subAccounts": {
            "subAccount": [{

                "agentOfRecord": []
            }]
        }
    }
}

在上面的例子中,两个键是空的“rateType”和“agentOfRecord”。如何从有效负载中删除这两个键。

预期的结果会是这样

{
    "transactionDetails": {
        "maintenanceType": null,
        "transactionDate": "2021-10-07T05:38:38.44-05:00"
    },
    "account": {
        "agentOfRecord": {
            "type": "true"

        },
        "subAccounts": {
            "subAccount": [{

                
            }]
        }
    }
}

我尝试了下面的代码,但没有工作它没有过滤实际的密钥

%dw 2.0
output application/json
---
payload filterObject ((value, key) -> (key as String != "Test")) 

【问题讨论】:

标签: json key dataweave mule4


【解决方案1】:

不直接使用变量filterList,使函数复用性更强。该变量可以替换为从配置或数据库中获得的列表。 此脚本应删除 filterList 中提到的所有“空”键。我使用了一个自定义的空函数,因为内置的 isEmpty() 函数还包含空对象,我不确定你是否想要。否则你可以使用内置版本。

%dw 2.0
output application/json
var filterList=["rateType", "agentOfRecord"]

fun isEmptyCustom(x)=
    x match  {
        case is Array -> sizeOf(x) == 0
        case is String -> sizeOf(x) == 0
        else -> false
    }


fun filterKey(k, v, f)= !isEmptyCustom(log("v",v)) or 
    !(f contains (log("k", k) as String))


fun filteKeyRecursive(x, f) = 
    x match {
        case is Object -> 
            x 
            filterObject ((value, key, index) ->  filterKey(key, value, f)) 
            mapObject  ($$): filteKeyRecursive($, f) 
        case is Array -> x map filteKeyRecursive($, f) 
        else -> x
  }
---
filteKeyRecursive(payload, filterList)

更新:修复了条件。

【讨论】:

  • 谢谢,我知道 var filterList 不在匹配逻辑中使用,而仅用于递归。此代码是否删除除“rateType”、“agentOfRecord”之外的所有空字段?
  • 我在答案中添加了解释。
  • 我的第一个答案出现了逻辑错误。现已修复。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-25
  • 2023-03-24
  • 1970-01-01
  • 1970-01-01
  • 2014-09-06
  • 1970-01-01
相关资源
最近更新 更多