0

我有以下json:

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

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

我有以下代码:

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

它给了我以下错误:

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

我努力了:

  • 设置folderName为“/assets/i18n/en.json”
  • 重建并重新连接我的测试手机
  • 使用 HTTP 和 with this.http.get("~/app/assets/i18n/en.json").toPromise().then(res => console.log("http???", res)).catch(err => console.log("err:", err));
  • 打印目标文件而不解析它(它是空的......)

但错误保持不变。

update1 看来,遗憾的是,该文件不存在。这段代码:

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

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

返回一个假。

虽然看到项目文件提供的图片。 在此处输入图像描述(proided 的代码在 app.component.ts 中,在 AppComponent 的构造函数中)这可能是什么问题?

update2:更新了我webpack.config.js的复制 .json 文件:

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

但仍然没有运气。该文件仍然不存在...

更新3: 这越来越荒谬了......该文件可以作为标准json文件导入,但Nativescript lib仍然看不到它。

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));

这会产生以下输出:

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

2 回答 2

1

AFAIK,路径必须分开;您不能直接请求具有相对路径的文件。

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

console.log(
 knownFolders.currentApp().getFolder(folderName).getFile(fileName).readTextSync(),
);
于 2019-12-16T17:02:01.390 回答
1

我在开发应用程序时遇到了类似的情况。问题是未授予文件权限。

无需任何许可即可完美运行的另一种方法是从 url 获取 JSON 并通过它工作。

于 2019-12-18T08:26:14.717 回答