WinJS加载本地json文件
我正在为此努力奋斗.
我找不到从WinJS应用程序中的子文件夹打开简单json文件的方法.
I cannot find a way to open a simple json file from a subfolder in my WinJS App.
我尝试了Ajax和WinJS.xhr,但都无济于事.
I have tried Ajax and WinJS.xhr, both to no avail.
我还考虑过使用.NET中的File.Open之类的文件以老式"方式打开文件,但是除了WinJS.Application.local.readText以外,我都找不到其他东西,我都尝试使用绝对和相对路径.
I have also looked into opening the file the "old fashioned" way with something like File.Open in .NET, but I couldn't find anything besides WinJS.Application.local.readText, which I tried with both an absolute and a relative path.
我在这里尽头了,有人可以共享一个有效的代码段吗?
I'm at the end of my rope here, does anyone have a working snippet that you can share?
您可以使用以下格式的URL来引用应用程序包中的文件:
You can refer to files in the app package using URLs in the form:
ms-appx:///data/data.json
(请注意,有三个/
字符-如果您错过了第三个字符,则会遇到问题)
(Notice that there are three /
characters - if you miss the third one out, you'll have problems)
要读取和解析包含JSON对象的文件,可以使用Windows.Storage
名称空间中的对象.分三个步骤-获取指向文件的StorageFile对象,读取文件的内容,然后解析JSON数据.这是我用来执行此操作的代码:
To read and parse a file that contains a JSON object, you can use the objects in the Windows.Storage
namespace. There are three steps - to get a StorageFile object that points to the file, read the contents of the file and then parse the JSON data. Here is the code that I used to do this:
var url = new Windows.Foundation.Uri("ms-appx:///data/data.json");
Windows.Storage.StorageFile.getFileFromApplicationUriAsync(url).then(function (file) {
Windows.Storage.FileIO.readTextAsync(file).then(function (text) {
var parsedObject = JSON.parse(text);
// do something with object
});
});
有很多方法可以从文件中读取数据,但是我发现FileIO
对象是最方便的.上面的代码假定文件中存在一个JSON对象描述.如果您的文件每行包含一个对象,那么您将需要:
There are lots of ways of reading the data from the file, but I find the FileIO
object the most convenient. The code above assumes there is one JSON object description in the file. If you have a file that contains one object per line, then you'll need this:
var url = new Windows.Foundation.Uri("ms-appx:///data/data.json");
Windows.Storage.StorageFile.getFileFromApplicationUriAsync(url).then(function (file) {
Windows.Storage.FileIO.readLinesAsync(file).then(function (lines) {
lines.forEach(function (line) {
var parsedObject = JSON.parse(line);
// do something with object
});
});
});
这是一个细微的变化,它使用FileIO.readLinesAsync
方法创建字符串数组,每个字符串都被解析为JSON对象.
This is a slight variation that uses the FileIO.readLinesAsync
method to create an array of strings, each of which is parsed as a JSON object.