DEV Community

Cover image for isJsonStructure() CFML User-Defined Function
James Moberg
James Moberg

Posted on

3

isJsonStructure() CFML User-Defined Function

Apparently strings, numbers, true, false and null are considered valid JSON even though they consist of a single escaped value. (I recently discovered this while accepting API data from a third-party and they accidentally double-encoded the JSON body payload.

To prevent this issue from occurring again, I wrote a CFML User-Defined Function (UDF) to test whether a string can successfully parsed to an object and/or array (versus accepting an invalid simple value). Enjoy!

isJsonStructure(string, type="any")

https://gist.github.com/JamoCA/e153c2ea40bfd75b60d180fbb709fe5b

function comparisons between isJson and isJsonStructure

<cfscript>
// 2020-08-20 isJsonStructure(string, type=all);
// https://gist.github.com/JamoCA/e153c2ea40bfd75b60d180fbb709fe5b
public boolean function isJsonStructure(required string string, string type="any") output=false hint="I return true if the string is a JSON-serialized struct or array." {
if (not isJson(arguments.string)){
return false;
}
local.parsed = deserializeJson(arguments.string);
if (not local.keyExists("parsed")){
return false;
}
if (isStruct(local.parsed) and (not len(trim(arguments.type)) or listFindNoCase("any,struct,structure,object,record,dictionary,hashtable,hash table,keyed list,associative array", trim(arguments.type)))){
return true;
} else if (isArray(local.parsed) and (not len(trim(arguments.type)) or listFindNoCase("any,array,vector,list,sequence", trim(arguments.type)))){
return true;
}
return false;
}
</cfscript>

Top comments (0)

Retry later
Retry later