Get a local json file on NativeScript

后端 未结 4 799
伪装坚强ぢ
伪装坚强ぢ 2021-01-18 07:29

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 observab         


        
相关标签:
4条回答
  • 2021-01-18 08:09

    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.

    0 讨论(0)
  • 2021-01-18 08:10

    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.

    0 讨论(0)
  • 2021-01-18 08:16

    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

    0 讨论(0)
  • 2021-01-18 08:25

    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());
        }
    }
    
    0 讨论(0)
提交回复
热议问题