Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

read data from .json file (TypeScript)

Tags:

typescript

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?

like image 348
Igor K. Avatar asked Dec 11 '25 19:12

Igor K.


1 Answers

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);
}
like image 62
Fenton Avatar answered Dec 14 '25 09:12

Fenton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!