0

I need to iterate through a JSON object in JavaScript or jQuery that is returned from a PHP file with the a json_encode function call:

echo json_encode ($varDump);

The beginning of the JSON objects looks like the following:

["date","Rescription",{"date":"1715-05-03","description":"Edmund Halley observes total eclipse phenomenon \"Baily's Beads\""},{"date":"1765-05-03","description":"1st US Medical school opened"},{"date":"1797-05-03","description":"Jamaica discovered by Columbus"},{"date":"1802-05-03","description":"Washington, D.C., was incorporated as a city."},{"date":"1830-05-03","description":"1st regular steam train passenger service starts"},

I need to pull out the date and the description.
I tried the following but I am getting errors:

            count = data.length - 1;
            for(i=0; i < count; i++){
                $('#currentText').html(data.date[i]);
                $('#currentText').html(data.description[i]);
            }    

The value in count on my test case seems way high, as if it’s counting characters and FF says data.date is not an object.
How would I go about doing this?

Edited by mike_2000_17: Fixed formatting

1
Contributor
3
Replies
4
Views
7 Years
Discussion Span
Last Post by rouse
0

I made some progress and found the correct syntax for displaying the array, but I can't seem to output individual data elements.
For testing I wrote this function:

success: function(data){
                $('#currentText').append(data);
                
                count = data.length;
                for(i=2; i < count; i++){
                    $('#currentText').append(data[i].date);
                    $('#currentText').append(data[i].description);
                }
            }, //end success function

On my web page I see the first append as I expcted, the whole data structure.
For the second and third append, nothing appears

Any thoughts?

0

I now have a JSON file that looks like this:

["date","Rescription",{"date":"1715-05-03","description":"Edmund Halley observes total eclipse phenomenon \"Baily's Beads\""},{"date":"1765-05-03","description":"1st US Medical school opened"},{"date":"1797-05-03","description":"Jamaica discovered by Columbus"},

But the key seems misspelled for description, and statements like

console.log(data[4].date);
console.log(data[4].description);

produce an undefined error.

Edited by mike_2000_17: Fixed formatting

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.