1
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

4 Answers 4

2

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?

Sign up to request clarification or add additional context in comments.

1 Comment

It works for that because that is an array. If it's not an array, you can't loop over it.
1

Just make sure it's an array before you iterate

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

Comments

0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.