0

By help my last question got solved but still stuck..

After trying this I got an error on console log..

Error: Syntax error, unrecognized expression: [ { "id": 1, "name": "Bhavik", "phone": 9601109585 }, { "id": 2, "name": "Xyz", "phone": 1234567890 }, { "id": 3, "name": "Abc", "phone": 9876543210 } ]
[Break On This Error]   

throw new Error( "Syntax error, unrecognized expression: " + msg );  

jQuery code:

var list = { "Persons": data.d };
$(list.Persons).each(function (index) 
{
     alert( this.id + "\n" + this.name + "\n" + this.phone);
});

JSON array:

[
  {
    "id": 1,
    "name": "Bhavik",
    "phone": 9601109585
  },
  {
    "id": 2,
    "name": "Xyz",
    "phone": 1234567890
  },
  {
    "id": 3,
    "name": "Abc",
    "phone": 9876543210
  }
]  

I want to loop through the list.. Any ideas..

EDIT After @Vucko's suggestion I tried replacing data.d by the the JSON array itself and to my surprise it worked JSFiddle.. Any reason and solution for it..

Solved changed var list = { "Persons": $.parseJSON(data.d)};.. JSON response is not enough I guess.. We need to parse it also..

Community
  • 1
  • 1
Bhavik
  • 4,836
  • 3
  • 30
  • 45

1 Answers1

1

Your code has only one error :

var list = { "Persons": data.d };
                             ^

Change to :

var list = { "Persons": data };

JSFiddle

Vucko
  • 20,555
  • 10
  • 56
  • 107
  • data.d gives me the JSON array.. I tried a small change replacing data.d with the array.. [Have a look](http://jsfiddle.net/uR7m4/1/). Also I tried `var list = { "Persons": data };` as you recommend but the alert gives undefined.. – Bhavik Jul 19 '13 at 21:22
  • Shure, all that matters is that works. It all depends on how you use the JSON array and then you modify the code appropriate to that. Check the other questions about looping through JSON array ( [like this one](http://stackoverflow.com/questions/2342371/jquery-loop-on-json-data-using-each) ). – Vucko Jul 19 '13 at 21:25
  • @Bhavik var list = { "Persons": data.d }; $.each(list.Persons, function (index) { alert( index.id + "\n" + index.name + "\n" + index.phone); }); – Rooster Jul 19 '13 at 22:25