I develop game using TypeScript. I have level.json file, which generated by level editor. How I can load this file in my game and read data from it?
1 Answer
Simplistically speaking, you could load it with an AJAX call and parse the JSON:
function levelRequestListener () {
var levels = JSON.parse(this.responseText);
console.log(levels);
}
var request = new XMLHttpRequest();
request.onload = levelRequestListener;
request.open("get", "level.json", true);
request.send();
You could take this up a level by writing an interface to describe the levels structure so you could get type checking and auto-completion on the levels variable...
interface Level {
id: number;
name: string;
}
function levelRequestListener () {
var levels: Level[] = JSON.parse(this.responseText);
console.log(levels[0].name);
}