How can I use ColdFusion to work with JSON?
ColdFusion adds three functions that work with JSON: serializeJSON(), deserializeJSON(), and isJSON(). Let's look first at serializeJSON. You can take any arbitrary ColdFusion data and translate it into JSON using the function:
<cfset foo = arrayNew(1)> <cfset foo = "Ray"> <cfset foo = "Camden"> <cfset s = structNew()> <cfset s.age = 35> <cfset s.arr = foo> <cfset js = serializeJSON(s)>
This creates a JSON string that looks like so:
This could be passed to the client via AJAX. On the flip side, you can use deserializeJSON to translate a JSON string back into native ColdFusion data:
<cfset orig = deserializeJSON(js)>
And to be extra careful, you can first check to see if the string is valid JSON:
<cfif isJSON(js)> <cfset orig = deserializeJSON(js)> </cfif>
This question was written by Raymond Camden
It was last updated on July 1, 2008.