views:

58

answers:

4
var records = JSON.parse(JsonString);

for(var x=0;x<records.result.length;x++)
{
  var record = records.result[x];
  ht_text+="<b><p>"+(x+1)+" "
    +record.EMPID+" "
    +record.LOCNAME+" "
    +record.DEPTNAME+"  "
    +record.CUSTNAME
    +"<br/><br/><div class='slide'>"
    +record.REPORT
    +"</div></p></b><br/>";
}

The above code works fine when the JsonString contains an array of entities but fails for single entity. result is not identified as an array! Whats wrong with it?

http://pastebin.com/hgyWw5hd

+1  A: 

result is not an array. Do you see any square brackets in your JSON? no you do not. it does not contain any arrays.

{"result": {"ID":"30","EMPID":"1210308550","CUSTID":"1003","STATUS":"2","DATEREPORTED":"1273234502","REPORT":"this is one more report!","NAME":"Sandeep Savarla","CUSTNAME":"Collateral","LOCID":"4","LOCNAME":"Vijayawada","DEPTNAME":"SALES"}}

Can you show me what your "valid" json looks like when the function above works?

mkoryak
It works for this..http://pastebin.com/SeWKedyU
blacktooth
It works for that because that **is** an array. If it's not an array, you can't loop over it.
SLaks
Fine. I got it..Thanks.. :)
blacktooth
A: 

Your code is looping through records.result as if it were an array.
Since it isn't an array, your code does not work.

This simplest solution is to force it into an array, like this:

var array = 'length' in records.result ? records.result : [ records.result ];

for(var x = 0; x < array.length; x++) {
    var record = array[x];
    ...
SLaks
A: 

In your code result is an object, not an array. Wrap it's value in square brackets to make it an array:

{"result": [{"ID":"30","EMPID":"1210308550","CUSTID":"1003","STATUS":"2","DATEREPORTED":"1273234502","REPORT":"this is one more report!","NAME":"Sandeep Savarla","CUSTNAME":"Collateral","LOCID":"4","LOCNAME":"Vijayawada","DEPTNAME":"SALES"}]}
Matt
+1  A: 

Just make sure it's an array before you iterate

if ( 'undefined' == typeof records.result.length )
{
  records.result = [records.result];
}
Peter Bailey