Get a local json file on NativeScript

跟風遠走 提交于 2020-01-11 08:39:08

问题


How to get a local big json data?

I have tried this, but I had no success:

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

回答1:


Use the file-system module to read the file and then parse it with 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');
});

Here's a real life example of how I'm doing it in a NativeScript app to read a 75kb/250 000 characters big JSON file.




回答2:


TypeScript:

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());
    }
}



回答3:


As of TypeScript version 2.9.x and above (in NativeScript 5.x.x is using versions 3.1.1 and above) we can now use resovleJsonModule option for tsconfig.json. With this option, the JSON files can now be imported just as modules and the code is simpler to use, read and maintain.

For example, we can do:

import config from "./config.json";

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

All we need to do is to use TypeScript 2.9.x and above and enable the propety in tsconfig.json

// tsconfig.json
{
    "compilerOptions": {
        "module": "commonjs",
        "resolveJsonModule": true,
        "esModuleInterop": true
    }
}

A sample project demonstrating the above can be found here




回答4:


I just wanted to add one more thing, which might be even easier. You can simply write the content of your JSON file in a data.js file, or whatever name you would like to use, and export it as an array. Then you can just require the data.js module.



来源:https://stackoverflow.com/questions/32414119/get-a-local-json-file-on-nativescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!