Search code examples
javascriptjsonnode.jscoldfusiontitanium

Using JavaScript to handle query data serialized by ColdFusion 9 neatly?


ColdFusion's serializeJSON function sends a string like this:

{"COLUMNS":["COURSE","CONTID","CODE"],"DATA":[["Texting 101",41867,"T043"]]}

How do I access the data using javascript neatly?

var response = JSON.parse(this.responseText);
console.log(response["CODE"]); // this doesn't work of course, but is there any way?
console.log(response.DATA[0][1]) // this works but it's not readable

Is it possible to access the JSON data using the column names instead of the array positions? This is for Titanium Studio, so I have access to node (if that helps my cause).


Solution

  • I defined the serializeQueryByColumns attribute of serializeJSON like so:

    #serializeJSON(cfQueryVar, true)#

    However it will come out a little funky:

    {"ROWCOUNT":1,
     "COLUMNS":["COURSE","CONTID","CODE"],
     "DATA":{
        "COURSE":["Texting 101","Sexting for Seniors","OMFGLOL","Columbus Day"],
        "CONTID":[41867,10736,23034,28012],
        "CODE":["T043","SFS","OMGL0100","CDSTD"]
     }}
    

    But you can access it like so:

    ... Ti.UI.createHTTPClient ...
    var response = JSON.parse(this.responseText);
    label.text = "The 3rd Course is: ", response.DATA.COURSE[2];
    

    Citation

    I got this from Henry in the source GuaravS gave in his answer. I created a new answer because Henry's comment was a brief comment / not an answer, and I wanted to expand upon defining the serializeQueryByColumns value in serializeJSON.