在 NativeScript 上获取本地 json 文件

Get a local json file on NativeScript

如何获取本地大json数据?

我已经试过了,但是没有成功:

var sa = require("./shared/resources/sa.json");
var array = new observableArrayModule.ObservableArray(sa);

使用file-system模块读取文件,然后用JSON.parse()解析:

var fs = require('file-system');

var documents = fs.knownFolders.currentApp();
var jsonFile = documents.getFile('shared/resources/sa.json');
var array;
var jsonData;

jsonFile.readText()
.then(function (content) {
    try {
        jsonData = JSON.parse(content);
        array = new observableArrayModule.ObservableArray(jsonData);
    } catch (err) {
        throw new Error('Could not parse JSON file');
    }
}, function (error) {
    throw new Error('Could not read JSON file');
});

这是一个 real life example of how I'm doing it in a NativeScript app 用于读取 75kb/250 000 个字符的大 JSON 文件。

我只想再补充一件事,这可能更容易。您可以简单地将 JSON 文件的内容写入 data.js 文件,或者您想要使用的任何名称,然后将其导出为数组。然后你可以只需要 data.js 模块。

打字稿:

import {knownFolders} from "tns-core-modules/file-system";

export class Something {
    loadFile() {
        let appFolder = knownFolders.currentApp();
        let cfgFile = appFolder.getFile("config/config.json");
        console.log(cfgFile.readTextSync());
    }
}

从 TypeScript 版本 2.9.x 及更高版本(在 NativeScript 5.x.x 中使用版本 3.1.1 及更高版本)我们现在可以使用 resovleJsonModule 选项 tsconfig.json.使用此选项,JSON 文件现在可以像模块一样导入,并且代码更易于使用、阅读和维护。

例如,我们可以这样做:

import config from "./config.json";

console.log(config.count); // 42
console.log(config.env); // "debug"

我们需要做的就是使用 TypeScript 2.9.x 及更高版本并启用 tsconfig.json

中的属性
// tsconfig.json
{
    "compilerOptions": {
        "module": "commonjs",
        "resolveJsonModule": true,
        "esModuleInterop": true
    }
}

可以找到演示上述内容的示例项目here