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)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay