Recently, I have been diving into the world of JSON, JavaScript, and YUI while working on a homework assignment. The JSON packet I am dealing with has the following structure:
[{"id":"1234", "name":"some description","description":"url":"www.sd.com"}, {same format as previous one}]
I attempted an example using YUI to parse a JSON string like this:
var jsonString = '{"id":"1234", "name":"some description","description":"url":"www.sd.com"}';
var messages = [];
messages = YAHOO.lang.JSON.parse(jsonString);
When I tried it with the sample JSON string, everything worked fine. However, when attempting to do the same from my professor's web server, I encountered a parsing error. I suspect it may be due to his packet being surrounded by square brackets [] whereas mine is not in the example. I even tried:
YAHOO.lang.JSON.parse(professorResponse[0]);
but that also resulted in an error. I would appreciate any advice on the best practices for handling data received from a web server, especially in terms of formatting the data for successful parsing. As a newcomer in this field, I am eager to learn and start off on the right foot. Thank you.
Edit:
For parsing the response from the web server, I implemented this approach:
function sendRequest() {
var url = "class website&response=JSON";
var callback = {success:handleResponse, failure:handleFailure, timeout:5000};
var transaction = YAHOO.util.Connect.asyncRequest("GET", url, callback, null);
}
// This function is called when handleResponse checks if the response is JSON or XML
function parseJSONResponse(response) {
var messages = [];
try {
messages = YAHOO.lang.JSON.parse(response);
}
catch (e) {
alert("JSON parse failed");
return;
}
}
Despite following this method, I still encounter issues with parsing the JSON response successfully.