Not yet rated
Tags:

Problem

How can I use ColdFusion to work with JSON?

Solution

ColdFusion has native support for both creating and converting JSON data. These functions are: serializeJSON, deserializeJSON, and isJSON.

Detailed explanation

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 work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. Permissions beyond the scope of this license, pertaining to the examples of code included within this work are available at Adobe.

Report abuse

Related recipes