Posts

Showing posts with the label Dataweave

Dataweave Code to Sort Nested JSON Objects & Arrays

Image
This document covers Dataweave code to sort nested JSON objects and arrays. For this demonstration, we are using Mulesoft's Online Dataweave Playground - Link as an IDE. Let’s begin... Solution Preview Code Snippet %dw 2.0 fun sortObjectAndArray (inputPayload) = (   if(inputPayload is Object) (     inputPayload mapObject ((value, key, index) ->        (key): sortObjectAndArray (value)     ) orderBy $$   )   else if(inputPayload is Array) (     if(inputPayload[0] is Object)       inputPayload map ((item, index) ->          sortObjectAndArray (item)       )     else       inputPayload orderBy $   )   else inputPayload ) output application/json --- sortObjectAndArray (payload) Brief Explanation This code traverses through a nested JSON Object or Array input and sorts it. Here we have a user-defined function named sortObjectAndArra...

Dataweave Code to Validate All Key Values of an Object in JSON Array

Image
This document covers Dataweave code to validate all JSON key values in a JSON array. For this demonstration, we are using Mulesoft's Online Dataweave Playground - Link as an IDE. Let’s begin... Solution Preview Code Snippet %dw 2.0 output application/json import * from dw::Runtime import * from dw::core::Strings fun valRequiredAlphanum(value, key, len = 30) =  if (isEmpty(value)) fail(key ++ " is a required field; ")  else if (!(value matches /[A-Za-z0-9]+/)) fail(key ++ " can only contain alphanumeric values; ")  else "" fun valNum(value, key, len = 10) =  if (!(value matches /[0-9]+/)) fail(key ++ " can only contain number; ")  else if (!(sizeOf(value) <= len)) fail(key ++ " must be less than " ++ (len as String) ++ " digits; ")  else "" fun valList(value, key, list) =  if (isEmpty(list find value)) fail(key ++ " field has invalid selection; ")  else "" var validatedRecords = payload map...

Dataweave Code to Identify Duplicate Key Values in JSON Array

Image
This document covers Dataweave code to identify and flag duplicate field or key values in a JSON array. This code will treat the first copy as original and mark the remaining copies as duplicate. For this demonstration, we are using Mulesoft's Online Dataweave Playground - Link as an IDE. Let’s begin... Solution Preview Code Snippet %dw 2.0 output application/json fun getDistinctRecords(records, field) = flatten((records groupBy ((item, index) -> item[field])) pluck ((value, key, index) -> value) map ((item, index) -> item distinctBy ((item, index) -> item[field]))) var distincValues = getDistinctRecords(payload, "Username") var duplicates = payload -- distincValues --- (distincValues) ++ (duplicates map ((item, index) -> item ++ {"Duplicate Flag": "Yes"})) Brief Explanation The main logic for this problem revolves around the distinctBy function. But you are here because you al so found out about this function's limitation when dea...