Question

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).

Was it helpful?

Solution 2

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.

OTHER TIPS

I created cfquery-to-json to create alternate JSON formats for ColdFusion queries. Take a look at ArrayColleciton, which will convert the query object to an array of structs. The keys for the structs are the column names from the query.

{ "data":[ { "course":"Texting 101", "contid":41867, "code":"T043" } ] }

This allows you to easily reference data[x].course.

Check out the answer to the question putting selected values from the JSON. You should then be able to access the column as expected.

public array function queryToArray( required query qry ) {
var columns = arguments.qry.getColumnNames();
var OutputResult = [];

for( var i = 1; i LTE qry.recordCount; i++ ) {
    var obj = {};

    for( var k = 1; k LTE arrayLen( columns ); k++ ) {
        structInsert( obj, columns[ k ], arguments.qry[ columns[ k ] ][ i ] );
    }

    arrayAppend(OutputResult, obj );
}

return OutputResult;
}

Access the function as below:

<cfset myJSON = queryToArray( myquery ) />
<cfoutput>#serializeJSON( myJSON )#</cfoutput>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top