Nativescript无法读取JSON文件
我有以下json: …/src/app/assets/i18n/en.jsonNativescript无法读取JSON文件,json,nativescript,angular2-nativescript,angular-nativescript,Json,Nativescript,Angular2 Nativescript,Angular Nativescript,我有以下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.p
{
"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>)
返回一个false
尽管如此,请参见项目文件中提供的图片。
(提供的代码位于AppComponent的构造函数中的app.component.ts中)
这里有什么问题
更新2:
更新我的webpack.config.js
以复制.json文件:
new CopyWebpackPlugin([
{ from: { glob: "fonts/**" } },
{ from: { glob: "**/*.jpg" } },
{ from: { glob: "**/*.json" } },
{ from: { glob: "**/*.png" } },
], { ignore: [`${relative(appPath, appResourcesFullPath)}/**`] }),
但还是没有运气。该文件仍然没有extist
更新3:
这太荒谬了。。。该文件可以作为标准json文件导入,但Nativescript库仍然看不到它
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
好吧,这条路必须分开;不能直接请求具有相对路径的文件
const folderName=“资产/i18n”;
const fileName=“en.json”;
console.log(
knownFolders.currentApp().getFolder(folderName).getFile(fileName).readTextSync(),
);
好的,路径必须拆分;不能直接请求具有相对路径的文件
const folderName=“资产/i18n”;
const fileName=“en.json”;
console.log(
knownFolders.currentApp().getFolder(folderName).getFile(fileName).readTextSync(),
);
在使用应用程序时,我面临类似的情况。问题是没有授予文件权限
另一种不需要任何许可就能完美工作的方法是从url获取JSON并通过它工作。我在使用应用程序时也面临类似的情况。问题是没有授予文件权限
另一种不需要任何权限就能完美工作的方法是从url获取JSON并进行处理。遗憾的是,这会产生相同的空字符串,而不是文件内容。只有当文件不存在时,它才能返回空字符串。是否确保文件存在-
file.exists(path.join(knownFolders.currentApp().getFolder(folderName.path,fileName))
?如果不是,可能是webpack没有绑定JSON文件。你可能需要调整你的网页配置。是的,我也试过这么做,但还是没有成功。文件不会被复制可能是因为某些原因?遗憾的是,这会导致相同的空字符串而不是文件内容。只有当文件不存在时,它才能返回空字符串。是否确保文件存在-file.exists(path.join(knownFolders.currentApp().getFolder(folderName.path,fileName))
?如果不是,可能是webpack没有绑定JSON文件。你可能需要调整你的网页配置。是的,我也试过这么做,但还是没有成功。文件不会被复制,可能是因为某些原因?所以我需要提示用户允许应用程序查看其内部?有没有办法不这样做?将这些文件放在公共API后面听起来是一个非常糟糕的解决方法。我不想维护一个服务器来访问手机上已有的文件,所以我需要提示用户允许应用程序查看其内部?有没有办法不这样做?将这些文件放在公共API后面听起来是一个非常糟糕的解决方法。我不想维护一个服务器来访问手机上已有的文件
JS: config: This is a translated line
JS: exists? false