Last active
September 8, 2021 18:59
-
-
Save JamoCA/25dc0b3133b0d9a890979ccf47e321e4 to your computer and use it in GitHub Desktop.
ColdFusion isStructPathValid() User-Defined Function - Returns true if deeply nested path exists (cfml/java)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!--- 20210908 isStructPathValid(struct, name) - Returns true if deeply nested path with a non-NULL value exists | |
Written to solve this Adobe ColdFusion Community question | |
https://community.adobe.com/t5/coldfusion-discussions/fun-with-isdefined-vs-keyexists/m-p/12368900#M189750 | |
This UDF could be easily modified to return the resultant key's value if it exists and fallback to returning NULL or a empty string if it doesn't. | |
NOTE: Doesn't natively work with Lucee since Lucee doesn't bundle org.apache.commmons.beanutils library. | |
---> | |
<cfscript> | |
boolean function isStructPathValid(required struct struct, required string name) output=false hint="Returns true if deeply nested path with a non-NULL value exists" { | |
if (not request.keyExists("isStructPathValid_propertyUtils")){ | |
request["isStructPathValid_propertyUtils"] = createObject("java", "org.apache.commons.beanutils.PropertyUtils"); | |
} | |
local.test = request["isStructPathValid_propertyUtils"].getNestedProperty(arguments.struct, arguments.name); | |
return local.keyExists("test") ? true : false; | |
} | |
apiResponse = [ | |
"data": [ | |
"errors": [ "surname is invalid" ], | |
"nullTest": javacast("null", 0) | |
] | |
]; | |
</cfscript> | |
<cfdump var="#apiResponse#" label="Sample object (with null item)"> | |
<cfoutput> | |
<h2>isStructPathValid( apiResponse, "data.errors" )</h2> | |
#isStructPathValid( apiResponse, "data.errors" )# | |
<h2>isStructPathValid( apiResponse, "data.nullTest" )</h2> | |
#isStructPathValid( apiResponse, "data.nullTest" )# | |
<h2>isStructPathValid( apiResponse, "data.does_not_exist" )</h2> | |
#isStructPathValid( apiResponse, "data.does_not_exist" )# | |
</cfoutput> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment