How can I use ColdFusion to work with JSON?

JSON stands for JavaScript Object Notation. You can think of it as a way to represent data (and type of data) in a string. This makes the data easy to pass between the client side and the server side and is a favorite format for use with AJAX based applications.

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[1] = "Ray">
<cfset foo[2] = "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:

{"AGE":35.0,"ARR":["Ray","Camden"]}

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.

Categories

Strings
JavaScript

Comments

comments powered by Disqus