如何忽略DataWeave Mule ESB中的空对象 [英] How to ignore empty objects in DataWeave Mule esb

查看:105
本文介绍了如何忽略DataWeave Mule ESB中的空对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在转换我的有效载荷.我已经知道了这里的情况.

I am working on transforming my payload. I have got the situation here.

输入有效负载如下所示:-

Input payload looks like this below one:-

{
 "address": {
    "city": "bab",
    "company_name": "asdast",
    "country_code": "sam",
    "location": {
    "city": null,
    "state": null
  }
}}

我使用了%output application/json skipNullOn = "everywhere",它会像下面这样返回JSON

I used %output application/json skipNullOn = "everywhere" it returns me JSON like below

{
 "address": {
"city": "bab",
"company_name": "asdast",
"country_code": "sam",
"location": { }
}}

但是如果位置对象中的所有字段都为空,我不想有空的位置对象.我期望这样的事情

But I don't want to have empty location object if all fields in location objects are empty.I am expecting something like this

{   
"address": {
"city": "bab",
"company_name": "asdast",
"country_code": "sam"
}}

推荐答案

这是一种递归解决方案,我在直接方法似乎难以理解后得出:

This is a recursive solution I arrived at after the direct approach seemed hard to understand:

%dw 1.0
%output application/json

%function acceptable(value) (
    (value default {}) != {}
)

%function filterKeyValue(key, value) (
    ((key): value) when acceptable(value)
)

%function removeFields(o) o
    unless o is :object
    otherwise o mapObject
        (filterKeyValue($$, removeFields($)))

---
removeFields(payload)

这是我开始使用的直接方法:

Here's the direct approach I started with:

%dw 1.0
%output application/json

%function skipNulls(o) o 
    unless o is :object 
    otherwise o mapObject {
        (($$): $) when ($ != null)
    }

%function skipEmpty(o) o mapObject {
        (($$): $) when ($ != {})
    }

---
address: skipEmpty(payload.address
    mapObject { 
        ($$): skipNulls($)
    }
)

请注意,我们将skipNullOn="everywhere"放在了%output指令上,并删除了函数中的空字段.这使我们可以确保在检查包含对象是否为空之前 删除空值.

Note that we dropped skipNullOn="everywhere" on the %output directive, and removed null fields in a function instead. This allows us to make sure the nulls get removed before we check if the containing object is empty.

该函数(在两种解决方案中)均有效,因为 mapObject 允许我们遍历对象字段,并且仅在它们满足特定条件时才将它们包括在结果对象中.

The function (in both solutions) works because mapObject allows us to loop over the object fields, and include them in the result object only if they meet a certain condition.

这篇关于如何忽略DataWeave Mule ESB中的空对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆