Displaying Dictionary in Javascript Object
I'm returning this response from my server:
callback({"City": "Miami", "State": "FL", "Street": "9th Street", "Name": "Big 12", "Zip": "65201", "Lat": -48.219999999999999, "Telephone": "5732168906", "Long": 32.0, "Events": "[{\"End Time\": \"2011-01-22 23:36:31\", \"Name\": \"Margaritas\", \"Start Time\": \"2011-01-22 15:36:31\"}, {\"End Time\": \"2011-01-22 19:36:39\", \"Name\": \"Dollar Bottles\", \"Start Time\": \"2011-01-22 15:36:39\"}, {\"End Time\": \"2011-01-23 23:36:31\", \"Name\": \"All You Can Drink\", \"Start Time\": \"2011-01-23 15:36:31\"}]"})
Here is where I'm attempting to parse the response and display it within my "tonight-list". With data.Events, I get the entire array of dictionaries displayed on screen.
function callback(data){
console.log(data);
$("#tonight-list").append("<li role='option' tabindex='0' class='ui-开发者_Go百科li ui-li-static ui-btn-up-c'>Starts:" +
data.Events +
"<li>");
However, I cannot figure out how to access each element (Start Time, End Time, Name, etc.). When I try data.Events[0], it gives me just the first character from data.Events.
How do I access each dictionary key in the array of Events? I just cannot figure out the syntax - it would be nice if I could see all the options on this object type. Thanks for the help in advance!
Make the Events
in the JSON response a real array instead of a string, then you can use it like this:
var obj = JSON.parse(reponseText);
var event = obj.Events[0];
alert(event["End Time"]); // hurray
JSON response
callback({
"City": "Miami",
"State": "FL",
"Street": "9th Street",
"Name": "Big 12",
"Zip": "65201",
"Lat": -48.219999999999999,
"Telephone": "5732168906",
"Long": 32.0,
"Events": [{
"End Time": "2011-01-22 23:36:31",
"Name": "Margaritas",
"Start Time": "2011-01-22 15:36:31"
},
{
"End Time": "2011-01-22 19:36:39",
"Name": "Dollar Bottles",
"Start Time": "2011-01-22 15:36:39"
},
{
"End Time": "2011-01-23 23:36:31",
"Name": "All You Can Drink",
"Start Time": "2011-01-23 15:36:31"
}]
});
JSON dude! just return valid JSON from your server and use evalJSON. Then you can access each object via their corresponding keys.
edit:
basically do,
data.responseText.evalJSON();
精彩评论