开发者

problem parsing JSON Strings

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


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?


Just make sure it's an array before you iterate

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


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];
    ...


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"
  }]
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜