Get a local json file on NativeScript

calebeaires picture calebeaires · Sep 5, 2015 · Viewed 7k times · Source

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

Answer

Emil Oberg picture Emil Oberg · Sep 5, 2015

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.