Subject: Trouble parsing JSON
I am getting a JSON response from a HTTP request but when I attempt to parse it nothing happens...
here is the JSON that I am parsing:
[{"event_id":"test1","status":"closed"},{"event_id":"test2","status":"open"}]
The code:
Titanium.API.log(this.responseText);
document.getElementById('html').innerHTML = this.responseText;
var results = JSON.parse(this.responseText);
$.each(results,function(a) {
Titanium.API.log(results[a].event_id);
}
the HTML text works fine but after I attempt to parse it to JSON nothing happens
Any help would be appreciated
Thanks
Comments are currently closed for this discussion. You can start a new one.
2 Posted by Stephen G on 09 Feb, 2010 03:52 PM
Might be a silly question, but if you are using "JSON.parse", do you have json2.js included in your project?
You can see here
http://jsbin.com/alahi3/edit
that your exact JSON string does get properly parsed by that library (but it has to exist !!)
3 Posted by Kevin Krut on 09 Feb, 2010 06:50 PM
Stephen,
Thanks for the response.
Yes, I have included json2.js. I'm wondering if my loop to read the json is incorrect. I'll try extracting a few values without a loop and see what happens.
4 Posted by Stephen G on 09 Feb, 2010 06:58 PM
as long as you are including jQuery, then there is nothing wrong with your $.each() statement, although the use of "a" and "results[a]" isn't needed (you can just say "this" and that's the item in the index getting enumerated)
I'd suggest putting
Titanium.API.log(JSON.parse(this.responseText));
and seeing if you get:
[object Object]
spit out on the console.... if you do or don't is telling you the string is properly getting parsed :-)
5 Posted by Kevin Krut on 16 Feb, 2010 06:10 PM
I'm not sure why, but the problem seems to have been in the each loop.
I replaced it by this and it all worked fine:
for (var x = 0; x<results.length; x++)
{
}