How to remove empty array objects from dataweave response

为君一笑 提交于 2020-06-13 11:24:31

问题


I have a use case to remove empty json objects from dataweave response.

The dw response after transformation will be like

{
   "remuneration": {
     "allowance": [
       {   
       }
     ]
   },
   "identifiers": {
     "employeeId": "1",
     "id": "E001",
     "payrollId": "901",
     "username": "sample"
   },
   "employment": {
   }
 }

I want the empty objects to be removed from the output.

Expected output:

{
   "identifiers": {
     "employeeId": "1",
     "id": "E001",
     "payrollId": "901",
     "username": "sample"
   }
 }

DWL script

%dw 1.0

 %output application/json skipNullOn="everywhere"
 ---
 {
   (remuneration: {
     (allowance: (payload.remunerations default []) map ((remuneration , indexOfRemuneration) -> {
       amount: remuneration.amount,
       compensationElement: remuneration.compensationElement,
       compensationPlan: remuneration.compensationPlan,
       currency: remuneration.currency
     }) filter $ != {}) when (sizeOf (payload.remunerations)) != 0
     }),
   (identifiers: {
     employeeId: payload.worker.employeeId,
     id: payload.worker.id,
     payrollId: payload.worker.payrollId,
     username: payload.worker.username
   }) when payload.worker != null,
   (employment: {
     nboxDescription: payload.worker.nboxDescription,
     nboxPerformance: payload.worker.nboxPerformance,
     nboxPotential: payload.worker.nboxPotential
   }) when payload.worker != null
 }

回答1:


There is no out of the box way to do that but I built a function that does that

%dw 1.0
%output application/json

%function filterEmpty(value) 
  value match {
    object is :object -> 
      object mapObject {($$) : filterEmpty($)} mapObject ( {($$) : $} when not ($ is :empty) otherwise {}),
    array is :array -> 
       array map filterEmpty($) filter not ($ is :empty)
      ,
    default -> $
  }

---
filterEmpty(payload)


来源:https://stackoverflow.com/questions/53043075/how-to-remove-empty-array-objects-from-dataweave-response

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!