3

isJsonStructure() CFML User-Defined Function

 3 years ago
source link: https://dev.to/gamesover/isjsonstructure-cfml-user-defined-function-1kg9
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
Cover image for isJsonStructure() CFML User-Defined Function

isJsonStructure() CFML User-Defined Function

Aug 20

・1 min read

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>


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK