Reputation: 185
EDIT: sorry, had the code ridden with errors. changed it now
Ive been trying to extract some JSON data from a github link to put it in a html file, but everytime I try to do so (with the code below), I get an Uncaught TypeError: cannot read property "value" of null. This even though "value" (in the Json file) certainly is not null.
What is going wrong here?
Thanks
you can check out the json file i put on github https://github.com/BearsAreFriendly/PolitiekeHelderheid/blob/master/kamerleden.json . I am quite certain that "value" has been defined
var section = document.querySelector("section");
var requestURL = 'https://github.com/BearsAreFriendly/PolitiekeHelderheid/blob/master/kamerleden.json';
var request = new XMLHttpRequest();
request.open('GET', requestURL);
request.responseType = 'json';
request.send();
request.onload = function(){
var phdata = request.response;
showKamerleden(phdata);
}
function showKamerleden(jsonObj) {
var kamerleden = jsonObj["value"];
for (var i = 0; i < kamerleden.length; i++) {
var myPara1 = document.createElement('p');
myPara1.textContent = kamerleden[i].Id;
section.appendChild(myPara1);
}
}
this should print out the id's. instead I get my mentioned error code
Upvotes: 1
Views: 943
Reputation: 26
I believe you may not actually be receiving any JSON data from GitHub, but HTML. When my browser requests a GitHub page the response content type is Content-Type: text/html
. Your request URL should respond with JSON in order for it to be usable. When you request the GitHub URL you are likely getting other stuff (such as HTML), but not JSON.
For example, this url serves JSON data only: https://my-json-server.typicode.com/typicode/demo/posts
It has Content-Type: application/json
when I inspect the page in dev tools under the network section
Modifying your code to add the url below works perfectly.
var section = document.querySelector("section");
var requestURL = 'https://my-json-server.typicode.com/typicode/demo/posts';
var request = new XMLHttpRequest();
request.open('GET', requestURL);
request.responseType = 'json';
request.send();
request.onload = function(){
var phdata = request.response;
/* showKamerleden(phdata); */
document.write(JSON.stringify(phdata) )
}
Upvotes: 1
Reputation: 36
It isn't "value" that it is null, jsonObj is null.
Hence the error 'cannot read property "value" OF null'
I suggest you output and analyse the request in the callback
console.log(request)
Upvotes: 0
Reputation: 492
try this
var kamerledens = jsonObj.value;
instead of
var kamerledens = jsonObj["value"];
and also you should use a loop to go through all ids
function showKamerleden(jsonObj) {
var kamerledens = jsonObj.value;
for (var i = 0; i < kamerledens.length; i++) {
var myPara1 = document.createElement('p');
myPara1.textContent = kamerledens[i].Id;
section.appendChild(myPara1);
}
}
Edited:
Try moving
request.send();
after the onload
function
Upvotes: 1