Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a local json file on NativeScript

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);
like image 282
calebeaires Avatar asked Sep 05 '15 14:09

calebeaires


People also ask

What is the JSON file extension?

JSON (JavaScript Object Notation) is an open standard file format for sharing data that uses human-readable text to store and transmit data. JSON files are stored with the . json extension. JSON requires less formatting and is a good alternative for XML.


1 Answers

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.

like image 79
Emil Oberg Avatar answered Oct 28 '22 00:10

Emil Oberg