Subject: Trouble parsing JSON

Original Post Kevin Krut's Avatar

Kevin Krut

09 Feb, 2010 05:48 AM via web

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

  1. 2 Posted by Stephen G on 09 Feb, 2010 03:52 PM

    Stephen G's Avatar

    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 !!)

  2. 3 Posted by Kevin Krut on 09 Feb, 2010 06:50 PM

    Kevin Krut's Avatar

    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.

  3. 4 Posted by Stephen G on 09 Feb, 2010 06:58 PM

    Stephen G's Avatar

    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 :-)

  4. 5 Posted by Kevin Krut on 16 Feb, 2010 06:10 PM

    Kevin Krut's Avatar

    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++)
    {

    Titanium.API.log(results[x].event_id);
    Titanium.API.log(results[x].status);
    

    }

Comments are currently closed for this discussion. You can start a new one.

Recent Discussions

13 Mar, 2010 01:38 PM
13 Mar, 2010 12:39 PM
13 Mar, 2010 11:06 AM
13 Mar, 2010 10:58 AM
13 Mar, 2010 09:02 AM