Ren44 Ren44 - 2 months ago 23
Javascript Question

Parsing Coldfusion JSON using javascript function - Uncaught ReferenceError: WddxRecordset is not defined

I am attempting to parse Coldfusion JSON data to make it look "normal"
ColdFusion json:

{"ROWCOUNT":3,"COLUMNS":["ROWID","REL","DATE","FOA","TITLE","APPRECEIPE","OPENING","KEYWORDS","DOC","PURPOSE","APP","NAME","PURPOSE"],"DATA":{"ROWID":[24842,24841,23780],"REL":["032","031","108"],
...

Searched on the web and found this link:

http://www.tysoncadenhead.com/blog/parsing-coldfusion-json-on-the-client-side#.V-UpKfkrKUk

He offers to use this function:

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;
};


Here is my code

<cfset jsonURL = SerializeJSON(SmartGuideSearchRet,true)>
<cfset URLd = #SmartGuideSearchRet#> //My CF Struct
<script>
<cfoutput>
var #toScript(URLd,"URLd")#;
</cfoutput>
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;
};
ujsonURL = URLd.parseCFJSON();
console.log(ujsonURL);
</script>


My console is giving me this error
Uncaught ReferenceError: WddxRecordset is not defined


When I try to feed the json coldfusion data to this function like this:

<script>
<cfoutput>
var #toScript(URLd,"URLd")#;
</cfoutput>
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;
};
ujsonURL = jsonURL.parseCFJSON();
console.log(ujsonURL);
</script>


I am getting this error:

Uncaught TypeError: Cannot read property 'length' of undefined


at this line

for (var j = 0; j < data.DATA.length; j++) {


I am doing something wrong and I am really stumped. Any help would be appreciated. I could be using the js function completely wrong (still learning).

Answer

Well I figured out what was going wrong here.

This <cfoutput> var #toScript(jsonURL,"jsonURL")#; </cfoutput> Was not parsing correctly. I changed it to eval() so my updated script looks like this and returns perfectly.

<script>
mydata = eval(<cfoutput>#jsonURL#</cfoutput>)
<cfoutput>
</cfoutput>
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;
};
mydata = mydata.parseCFJSON();
console.log(mydata);
alert(mydata);
</script>