Nativescript cannot read JSON file

532 Views Asked by At

I have the following json:

.../src/app/assets/i18n/en.json

{
  "TEST": "This is a some test data in a json file"
}

I have the following code:

const folderName = "assets/i18n/en.json";
knownFolders.currentApp().getFile(folderName).readText().then(a => console.log("json file: "+ JSON.parse(a))));

It gives me the following error:

ERROR Error: Uncaught (in promise): SyntaxError: Unexpected end of JSON input
JS: SyntaxError: Unexpected end of JSON input
JS:     at JSON.parse (<anonymous>)

I have tried:

  • Set folderName to "/assets/i18n/en.json"
  • Rebuild, and reconnect my testing phone
  • Use HTTP and with this.http.get("~/app/assets/i18n/en.json").toPromise().then(res => console.log("http???", res)).catch(err => console.log("err:", err));
  • print the object file without parsing it (it's empty...)

But the error stays the same.

update1 it seems, that the file, sadly, does not exists. this code:

const folderName = "assets/i18n";
const fileName = "en.json";

console.log("exists?", File.exists(folderName + "/" + fileName));

returns a false.

Although see the picture provided from the project files. enter image description here(the code proided is in app.component.ts, in the constructor of AppComponent) What can be the problem here?

update2: updated my webpack.config.js to copy .json files:

new CopyWebpackPlugin([
                { from: { glob: "fonts/**" } },
                { from: { glob: "**/*.jpg" } },
                { from: { glob: "**/*.json" } },
                { from: { glob: "**/*.png" } },
            ], { ignore: [`${relative(appPath, appResourcesFullPath)}/**`] }),

but still no luck. The file still does not extist...

Update3: This is getting ridiculous... the file can be imported as a standard json file, but the Nativescript lib still does not see it.

import { File } from "tns-core-modules/file-system";
import config from "./assets/i18n/hu.json";
....

        const folderName = "./assets/i18n";
        const fileName = "hu.json";
        console.log("config:", config.test)
        console.log("exists?", File.exists(folderName + "/" + fileName));

this produces the following output:

JS: config: This is a translated line  
JS: exists? false
2

There are 2 best solutions below

3
Ian MacDonald On

AFAIK, the path must be split; you can't request a file with a relative path directly.

const folderName = "assets/i18n";
const fileName = "en.json";

console.log(
 knownFolders.currentApp().getFolder(folderName).getFile(fileName).readTextSync(),
);
1
macsys On

I face similar situation while working on an app. the issue was that the file permissions was not granted.

other way around which worked perfectly, without needing any permission was to fetch the JSON from a url and work through it.