如何在打字稿中读取json文件?

时间:2018-05-30 21:28:28

标签: javascript typescript

我试图从api.json获取对象,但是根据我已将declare module "*.json"添加到项目中的打字稿,它会抛出错误。我知道如何才能完成此任务?

api.json

{
  "Refills": {
    "getPatientInfo": "Refills/patientInfo/GetPatientInfo"
  }
}

index.ts

import {ModuleExecutor} from "./common/ModuleExecutor";
import {Identity} from "./common/Enums";
export class Index {

    private executor: ModuleExecutor = null;
    // Any string prepended with @ is handled by grunt before building the project
    // grunt dynamically reads the config/api.json and loads only the apis that are listed there
    // api.json consists of the API name and the folder path for grunt

    private _apisConfig: string = '@api'
    constructor(identity: string) {
        this.executor = new ModuleExecutor(Identity[identity]);
        const apiConfig = JSON.parse(this._apisConfig);
        console.log('API',  apiConfig);
        for (const module in apiConfig) {
            if (apiConfig.hasOwnProperty(module)) {
                this[module] = {};
                for (const api in apiConfig[module]) {
                    if (apiConfig[module].hasOwnProperty(api)) {
                        this[module][api] = this.executor.execute(apiConfig[module][api]);
                    }
                }
            }
        }
    }
}

错误

SyntaxError: Unexpected end of JSON input
    at JSON.parse (<anonymous>)

编译的index.js文件

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const ModuleExecutor_1 = require("./common/ModuleExecutor");
const Enums_1 = require("./common/Enums");
class Index {
    constructor(identity) {
        this.executor = null;
        this._apisConfig = '';
        this.executor = new ModuleExecutor_1.ModuleExecutor(Enums_1.Identity[identity]);
        const apiConfig = JSON.parse(this._apisConfig);
        console.log('API', apiConfig);
        for (const module in apiConfig) {
            if (apiConfig.hasOwnProperty(module)) {
                this[module] = {};
                for (const api in apiConfig[module]) {
                    if (apiConfig[module].hasOwnProperty(api)) {
                        this[module][api] = this.executor.execute(apiConfig[module][api]);
                    }
                }
            }
        }
    }
}
exports.Index = Index;
//# sourceMappingURL=index.js.map

0 个答案:

没有答案