I have this json response that I want to parse in Javascript.
[{"video_source_id":100,"title":"YouTube Top Rated"},
{"video_source_id":101,"title":"YouTube Top Favorites"}]
I am new to Java Script, JSON. Whats the best way to parse and display it in a webpage?
Here is what I have, but I'm getting the following error
TypeError: Cannot read property '0' of undefined
in the line
document.getElementById("video_source_id").innerHTML = jsonObj.video_source_id[i];
Full code:
function loadJSON()
{
var http_request = new XMLHttpRequest();
try{
// Opera 8.0+, Firefox, Safari
http_request = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
var data_file = "/vcaWS/api/sources";
http_request.onreadystatechange = function(){
if (http_request.readyState == 4 )
{
// Javascript function JSON.parse to parse JSON data
var jsonObj = JSON.parse(http_request.responseText);
// jsonObj variable now contains the data structure and can
// be accessed as jsonObj.name and jsonObj.country.
for(var i=0;i<jsonObj.length;i++){
document.getElementById("video_source_id").innerHTML = jsonObj.video_source_id[i];
}
}
}
http_request.open("GET", data_file, true);
http_request.send();
}