Posts Tagged ‘WDDX’

Using WDDX instead of JSON to pass string of numbers

Tuesday, March 2nd, 2010

I’m a big fan of working with JSON data, but I did run into a snag that annoyed me a little the other day. Simply put JSON takes it upon itself to convert a string of numbers to a data type number. Normally I wouldn’t notice, but in this case I was trying to return a zip code that began with a zero. Each time it was returned, the zero had been eliminated. I returned it as just a string, ran it through the tostring() method and so forth. All with no luck.

In the end I packaged the zip code in a wddx packet.  This sets the value into some xml which types it as a string if it is a string despite the fact that it is all numbers.  When the data is returned it is returned as a string, keeping the leading zero.  I’ve set up a quick demo to illustrate this issue.  If you open it in the firebug console you will be able to see the JSON that is returned in comparison to the XML in the WDDX packet.

Also remember that if you are returning structs or arrays in JSON format you can store a WDDX packet as a JSON value-pair within the struct or array.  I’ve quickly showed this below.  If there is a way to control the data typing of JSON data I’d love to know how.

<!--- SET ZIP CODE --->
<cfset var zipcode = "02906">

<!--- CREATE A STRUCT --->
<cfset var data = structnew()>
<cfset data.success = true>
<cfset data.message = "This is some type of message.">
<cfset data.zipcode = "">

<!--- SET ZIP INTO A WDDX PACKET IN THE STRUCT --->
<cfwddx action="cfml2wddx" input="#zipcode#" output="data.zipcode">