Parsing Coldfusion JSON on the Client-side

code | 8-6-2011

I tend to fall in with Coldfusion programmers from time to time and while I actually really like the language and the community, the one thing that can make working with Coldfusion and JavaScript harder is how the language returns JSON.

Typical JSON looks something like this:

{
   "firstname": "Tyson",
   "lastname": "Cadenhead",
   "favoritelanguage": "JavaScript"
}

But Coldfusion encodes structs to look more like this:

{
    "COLUMNS": ["FIRSTNAME", "LASTNAME", "FAVORITELANGUAGE"],
    "DATA": [[
        "Tyson", "Cadenhead", "JavaScript"
    ]]
}

The problem with that is that JavaScript can't do much with that. The solution? I wrote a quick and dirty script that parses the Coldfusion JSON into the old-fashioned kind. All you need is this:

Object.prototype.parseCFJSON = function() {

   var result = [],
       data = this;

   for (var j = 0; j < data.DATA.length; j++) {
      result[j] = {};
      for (var i = 0; i < data.COLUMNS.length; i++) {
         result[j][data.COLUMNS[i].toLowerCase()] = data.DATA[j][i];
      }
   }

   return result;
};

If you include that bit of code in your script, anytime you get back a Coldfusion struct, you can simply encode it by running this:

myData = myData.parseCFJSON();

There you go... easy as pie!



About the Author

Tyson Cadenhead is a Senior JavaScript Developer at Aloompa. He lives in the greater Nashville area. His specialty is writing large, scalable JavaScript applications on the client and server side. His passions are for good design, usability, and clean, reusable code.

Tags: JavaScript Coldfusion

Related Posts:

comments powered by Disqus

Don't Miss Anything!

Sign Up For My Email Newsletter

I Wrote a Book!

Popular Posts