Notice: With the launch of Adobe Cookbooks, this site will no longer be accepting new entries or posting new content. Thanks to everyone who submitted content!

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 at 11:09:33 AM EDT.

CFML Referenced

<cfif>
IsJSON()
StructNew()
SerializeJSON()
DeserializeJSON()

Categories

JavaScript, Strings

Comments

Comment made by Andy Matthews on July 1, 2008 at 10:04 AM
There's also a JSON CFC over at RIAForge if you don't have ColdFusion 8: http://cfjson.riaforge.org/


Comment made by Raymond Camden on July 1, 2008 at 10:22 AM
Nod - that's a good one. The text of cookbook entries always refer to the most recent version of CF, but comments are perfect for this.