从 .json 文件(TypeScript)读取数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24301829/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 02:54:48  来源:igfitidea点击:

read data from .json file (TypeScript)

typescript

提问by Igor K.

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?

我使用 TypeScript 开发游戏。我有 level.json 文件,它是由关卡编辑器生成的。我如何在我的游戏中加载这个文件并从中读取数据?

回答by Fenton

Simplistically speaking, you could load it with an AJAX call and parse the JSON:

简单地说,您可以使用 AJAX 调用加载它并解析 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 levelsvariable...

您可以通过编写一个接口来描述级别结构来将其提升一个级别,以便您可以对levels变量进行类型检查和自动完成......

interface Level {
    id: number;
    name: string;
}

function levelRequestListener () {
    var levels: Level[] = JSON.parse(this.responseText);
    console.log(levels[0].name);
}