Posts

Showing posts from June, 2023

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...