1

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

Bhavik Kalal
  • 55
  • 1
  • 1
  • 9

3 Answers3

1

You should fetch the folder first, and you should do so using the knownFolders starting point.


import { knownFolders } from 'tns-core-modules/file-system';

knownFolders.currentApp().getFolder('shared').getFile('message.json').readText ...;
Ian MacDonald
  • 13,472
  • 2
  • 30
  • 51
1

If this file is in your source project - you have to make sure it gets saved by webpack.

In your webpack.config.js file

            new CopyWebpackPlugin([
                { from: { glob: "**/*.jpg" } },
                { from: { glob: "**/shared/*.json" } },
                { from: { glob: "**/*.png" } }
dashman
  • 2,858
  • 3
  • 29
  • 51
1

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);
    });
}
Shubham Panchal
  • 142
  • 2
  • 10