Dataweave Code to Validate All Key Values of an Object in JSON Array
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
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 ((item, index) ->
{
"Username":
if (try(() -> valRequiredAlphanum(item."Username","Username")).success) ""
else try(() -> valRequiredAlphanum(item."Username","Username")).error.message,
"Phone":
if (try(() -> valNum(item."Phone","Phone")).success) ""
else try(() -> valNum(item."Phone","Phone")).error.message,
"Subscribed":
if (try(() -> valList(item."Subscribed","Subscribed",["Yes", "No"])).success) ""
else try(() -> valList(item."Subscribed","Subscribed",["Yes", "No"])).error.message
} pluck ((value, key, index) -> value) joinBy ""
)
---
payload map ((item, index) -> item ++ {"Error": validatedRecords[index]})
Brief Explanation
The main logic for this problem revolves around the try and fail function. In the code snippet above, we have valRequiredAlphanum, valNum, and valList as user-defined functions that contain field-specific validation logic.
Since the try function outputs different payloads depending on success and error cases, we're exploiting the error scenarios by calling the fail function whenever any validation logic fails.
The rest of the logic is built around the collection and concatenation of all the error messages. After concatenation, the error message is appended as a new key-value pair to every object of the original JSON array. Feel free to modify the code however you like as per your use-case.
Sample Input
Output
{
"Username": "Alpha123",
"Name": "Alpha",
"Phone": "9999544448",
"Subscribed": "Yes",
"Error": ""
},
{
"Username": "Beta456",
"Name": "Beta",
"Phone": "9988755443",
"Subscribed": "No",
"Error": ""
},
{
"Username": "Charlie@789",
"Name": "Charlie",
"Phone": "A8899055446",
"Subscribed": "Yes",
"Error": "Username can only contain alphanumeric values; Phone can only contain number; "
},
{
"Username": "",
"Name": "Delta",
"Phone": "98765432101",
"Subscribed": "Ye s",
"Error": "Username is a required field; Phone must be less than 10 digits; Subscribed field has invalid selection; "
}
]
Comments
Post a Comment