简体   繁体   中英

Iterate over JSON array

I've read several examples of how to do what I want but none seem to work. I want to iterate over a JSON array but it's not working for me. When I look in chromes js console my data looks like this:

"[\r\n  {\r\n    \"EntryId\": 3,\r\n    \"Title\": \"Tiny Living For sales\",\r\n    \"Description\": \"This is a house for sale\",\r\n    \"AddressViewModel\": {\r\n      \"AddressId\": 3,\r\n      \"Street1\": null,\r\n      \"Street2\": null,\r\n      \"City\": \"Los Angeles\",\r\n      \"LocationId\": 5,\r\n      \"LocationName\": \"California\",\r\n      \"PostalCode\": null,\r\n      \"Phone\": null,\r\n      \"Latitude\": 34.052234,\r\n      \"Longitude\": -118.243685\r\n    },\r\n    \"EntryCategoryName\": \"Houses for Sale\",\r\n    \"EventStartDate\": null,\r\n    \"EventEndDate\": null\r\n  },\r\n  {\r\n    \"EntryId\": 2,\r\n    \"Title\": \"Tiny Living Workshop\",\r\n    \"Description\": \"This is a workshop\",\r\n    ...

And if I turn it into an object by doing so:

var myObject = eval('(' + locations + ')');

It looks like this (formated):

[
{
"EntryId": 3,
"Title": "Tiny Living For sales",
"Description": "This is a house for sale",
"AddressViewModel": {
  "AddressId": 3,
  "Street1": null,
  "Street2": null,
  "City": "Los Angeles",
  "LocationId": 5,
  "LocationName": "California",
  "PostalCode": null,
  "Phone": null,
  "Latitude": 34.052234,
  "Longitude": -118.243685
},
"EntryCategoryName": "Houses for Sale",
"EventStartDate": null,
"EventEndDate": null
},
{
"EntryId": 2,
"Title": "Tiny Living Workshop",

...

But when I try to iterate over it (either the raw JSON or the object) it gives me each letter of the JSON, not each object in the array

for (var i = 0; i < myObject.length; i++) { console.log(myObject[i]); }

Like so:

 "
 [
 \
 r
 \

Thanks

You evaluate the JSON and assign the result to "myObject", and then you attempt to iterate through "locations". It's no wonder that that doesn't work :-)

I figured it out. I was returning the JSON from my controller like this

return Json( jsonResults, "text/html");

I had to do this on a different controller to prevent IE from prompting the user to save the JSON results. Anyways, that was putting quotes around the data so it wasn't being parsed correctly.

So I am now returning:

return Json( jsonResults);

Hopefully I don't have the IE problem (tested in 9 and didn't see it)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM