Rolling your own JSON in ColdFusion? Be careful with returnFormat

This post is more than 2 years old.

Earlier today I blogged about rolling your own JSON solutions for ColdFusion. This mainly applied to folks running something less than ColdFusion 901 with the last hot fix. The original reader who requested the help had no problems using the jsonutil open source project, but ran into a problem as soon as he tried to combine it with ColdFuion's built in Ajax utilities. For example, this is a simple bound drop down he tried to use:

<cfselect name="sel_store" bind="" bindonload="true" display="STORENUMBER" value="STORENUMBER" />

His CFC was using jsontil and returning a JSON string. Upon running his application he got an error: Bind failed for select box sel_store, bind value is not a 2D array or valid serialized query.

So what went wrong? This is a case where even something like Firebug may not help if you don't pay careful attention. When you use ColdFusion's built in Ajax controls with bindings, it automatically converts the bind into a URL request. That request appends returnFormat=json. This tells ColdFusion that it should JSON-ify the result. But - his result was already JSON. So what you end up with is a JSON representation of a JSON string. Not good.

Luckily the fix is easy enough. Don't forget you can use "url" as a bound value as well. This allows you to point to any URL on your server. You can then point to the CFC and include method=getstores to tell ColdFusion to run that particular method. The critical part, though, is to also add: returnFormat=plain. This tells ColdFusion to not muck with the response and just leave it as is.

Raymond Camden's Picture

About Raymond Camden

Raymond is a senior developer evangelist for Adobe. He focuses on document services, JavaScript, and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can even buy me a coffee!

Lafayette, LA

Archived Comments

Comment 1 by Grant posted on 11/4/2010 at 3:21 AM

Iiiiiinteresting... I had no idea you could do this.

/me weeps bitterly because he's stuck on CF7

Comment 2 by Raymond Camden posted on 11/4/2010 at 3:23 AM

This was added in CF8. CF has 5 behaviors now:

1) No returnFormat: Return wddx, unless...
2) No returnFormat, type=xml: returns as plain (ie, dont touch the xml)
3) returnformat=wddx: return wddx
4) returnformat=json: json....
5) returnformat=plain: do nothing (so it better be simple data)