I'm having a problem with getting json data. I created 2 examples. One works, but the other doesn't. And guess which one I need? Yup, the one that doesn't work. Here is the code.
I have a web service that outputs json data but for some reason it add extra brackets [] to the string and it's also missing the single quotes ' '. If you look at the code that doens't work, you'll see that i'm manually removing the brackets and adding the single quotes. I have a div that i write the string to and it's valid Json data. If I take that string and manually declare a new variable with it, the jQuery.parseJSON works fine. But it I parse the newly created object, it doesn't work. Anybody have any ideas?
Works Fine
$.ajax({
type: "POST",
async: false,
contentType: "application/json; charset=utf-8",
url: "StudiesWebService.asmx/EventList",
data: "{}",
dataType: "json",
success: function(msg) {
var obj = jQuery.parseJSON('{ "id": 1, "title": "Jack STuff", "start": "\/Date(1318939200000)\/", "end": "\/Date(1318950000000)\/", "allDay": false }, { "id": 2, "title": "asdfasdfasdf", "start": "\/Date(1319025600000)\/", "end": "\/Date(1319025600000)\/", "allDay": false}');
var events2 = [];
events2.push({
title: obj.title,
allDay: obj.allDay,
start: 'Tue, 18 Oct 2011 10:00:00 EST',
end: 'Tue, 18 Oct 2011 11:00:00 EST'
});
callback(events2);
},
error: function(e) { $(".external-events").html("An Error Occured" + e); }
});
Doesn't Work:
$.ajax({
type: "POST",
async: false,
contentType: "application/json; charset=utf-8",
url: "StudiesWebService.asmx/EventList",
data: "{}",
dataType: "json",
success: function(msg) {
var myObj = new String(msg.d);
myObj = myObj.replace("[", "");
myObj = myObj.replace("]", "");
myObj = "'" + myObj + "'";
//at this point myObj output to this:
//'{"id":1,"title":"Mike STuff","start":"\/Date(1318939200000)\/","end":"\/Date(1318950000000)\/","allDay":false},{"id":2,"title":"asdfasdfasdf","start":"\/Date(1319025600000)\/","end":"\/Date(1319025600000)\/","allDay":false}'
var obj1 = jQuery.parseJSON(myObj);
alert(obj1.id); //alert doesn't come up
var events = [];
events.push({
title: obj1.title,
allDay: obj1.allDay,
start: 'Tue, 18 Oct 2011 10:00:00 EST',
end: 'Tue, 18 Oct 2011 11:00:00 EST'
});
callback(events);
},
error: function(e) { $(".external-events").html("An Error Occured" + e); }
});