How do I open a json file?

I tried the following but it didn’t work (console value was empty). What is the best way to load json data into the project? Many thanks.

let httpRequest = new XMLHttpRequest(); // asynchronous request
httpRequest.open("GET", "c:/test.json", true);
httpRequest.send();
httpRequest.addEventListener("readystatechange", 
project.data = function() {
    if (this.readyState === this.DONE) {
  	     // when the request has completed
         return JSON.parse(this.response);
     }
});
console.log(project.data);
var req = new XMLHttpRequest();
req.open("POST", "https://serverlocation.notarealwebsite");
req.send("{\"isHacked\":\"yes\"");

Use this? (I haven’t tested it yet)

Many thanks! I got the following to work;

fetch("file:///c:/test.json").then((response) => {
    response.json().then((data) => {
        console.log(data);
    })
})

If you want to use XMLHttpRequest, you need to add the event listener being sending, and this doesn’t refer to the HTTP request.

function openJson(file, callback) { // Since XMLHttpRequest is async, you will either need a callback function or use promises.
  var httpReq = new XMLHttpRequest();

  httpReq.onreadystatechange = function() { // you can still use addEventListener if you want
    if (httpReq.readyState === XMLHttpRequest.DONE) { // I didn't know about that enum
      if (httpReq.status == 200) { // Got 200 OK
        callback( JSON.parse(httpReq.response) );
      } else {
         // Error
      }
    }
  }

  httpReq.open("GET", "c:/test.json");
  httpReq.send();
}
Using promises
function openJSON(file) {
	return new Promise(function(resolve, reject) {
		var req = new XMLHttpRequest();

		req.onreadystatechange = function() {
			if (req.readyState === 4) {
				if (req.status === 200) {
					resolve( JSON.parse(req.response) );
				} else {
					reject(req.status);
				}
			}
		}

		req.open("GET", file);
		req.send();
	});
}

openJSON("c:/test.json").then(function(json) {
	console.log(json);
}).catch(function(status) {
	console.error(status);
});

@pumpkinhead Awesome - That worked great! Many thanks.

Does anyone know how I could pass project into the promises output? I’m struggling with this OOP stuff. Like so;

project.myVar = "qwerty";

openJSON("c:/test.json").then(function(json) {
	// log project var
	console.log(project.myVar);
	
	console.log(json);
}).catch(function(status) {
	console.error(status);
});

Many thanks :+1:

I think what you’re doing would work? If it doesn’t, try doing this:

project.myVar = "qwerty";
var _project = project; // declare local variable referring to project so promise function can see it

openJSON("c:/test.json").then((json) => { // newer, shorter syntax to write functions
  console.log(_project.myVar);
  console.log(json);
}).catch((status) => {
  console.error(status);
});

@pumpkinhead Yes! Thank you! Thank you! Thank you!

1 Like