2015-09-05 56 views

回答

7

使用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文件。

2

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

3

打字稿:

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()); 
    } 
} 
相关问题