hello I am trying to access a JSON file to my nativescrpt project. i tried this
let fs = require("tns-core-modules/file-system");
let documents = fs.knownFolders.currentApp();
function GetJsonData(callback) {
let filePath = documents.getFile("./shared/message.json");
let array;
let 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');
});
function showJsonData() {
GetJsonData((array) => {
console.log(array);
});
}
but it is failed to get data from JSON file
First you have to check that file is included in your webpack.config.js file in your project. Like @dashman said.
Find this in your webpack
new CopyWebpackPlugin([
{ from: { glob: "fonts/**" } },
{ from: { glob: "**/*.jpg" } },
{ from: { glob: "**/*.png" } },
], { ignore: [`${relative(appPath, appResourcesFullPath)}/**`] }),
and change to like this
new CopyWebpackPlugin([
{ from: { glob: "fonts/**" } },
{ from: { glob: "**/*.jpg" } },
{ from: { glob: "**/shared/*.json" } },
{ from: { glob: "**/*.png" } },
], { ignore: [`${relative(appPath, appResourcesFullPath)}/**`] }),
After that your code also lots of mistakes. Change like this
let fs = require("tns-core-modules/file-system");
let documents = fs.knownFolders.currentApp();
function GetJsonData(callback) {
let jsonFile = documents.getFile("./shared/message.json");
jsonFile.readText().then(function (content) {
try {
var jsonData = JSON.parse(content);
callback(jsonData);
} catch (err) {
callback(err);
throw new Error('Could not parse JSON file');
}
}, function (error) {
callback(error);
throw new Error('Could not read JSON file');
});
}
function showJsonData() {
GetJsonData((array) => {
console.log(array);
});
}