Currently, I'm working on a webpage project where I needed to access a JSON file in my JavaScript code. Here's the script I wrote for that purpose:
function xhrSuccess () { this.callback.apply(this, this.arguments); }
function xhrError () { console.error(this.statusText); }
function loadFile(url) {
var request = new XMLHttpRequest();
request.callback = readJSON;
request.onload = xhrSuccess;
request.onerror = xhrError;
request.open("GET", url, true);
request.send(null);
return request.callback();
}
function readJSON() {
console.log(this.responseText);
var myJsonObj = JSON.parse(this.responseText);
return myJsonObj;
}
This is how I call the function:
var jsonData = loadFile("http://localhost:8000/json/data.json");
But unfortunately, I keep encountering some errors and I am quite puzzled as to why they are happening.
Uncaught SyntaxError: Unexpected end of input
Uncaught SyntaxError: Unexpected token :
The first error seems to occur during the JSON parsing process.
I'm struggling to understand the exact meaning of these errors as they typically indicate syntax-related issues like missing semicolons or incorrectly formatted objects. However, since the error is being triggered at the JSON.parse()
line, I'm unsure about what could be causing it.
If anyone could provide some guidance, it would be greatly appreciated.
Also, here's the JSON data I'm trying to parse:
{ "data": [
{"file": "temp", "title": "This is a test", "date": "August 21, 2015"},
{"file": "temp2", "title": "This is also a test", "date": "August 20, 2015"},
{"file": "temp3", "title": "This is the final test", "date": "August 22, 2015"}
] }