javascript phonegap 读写json文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11136780/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
phonegap read and write json file
提问by Nick
I am looking to store a JSON file locally on IOS/Android in a Phonegap(Cordova) application.
我希望将 JSON 文件本地存储在 IOS/Android 上的 Phonegap(Cordova) 应用程序中。
Basically, I retrieve a JSON file from the server ($.GETJSON) and I want to first store the JSON file and then retrieve and modify it.
基本上,我从服务器 ($.GETJSON) 检索 JSON 文件,我想首先存储 JSON 文件,然后检索和修改它。
I've looked at FileWriter but I don't see a mimetype... the only example gives text files.
我看过 FileWriter 但我没有看到 mimetype ......唯一的例子给出了文本文件。
Thanks in advance!
提前致谢!
Nick
缺口
回答by Simon MacDonald
Nick, just use FileWriter.writeto save your JSON data to disk. JSON is a text based file anyway so there is no need to set the mime type. When you are ready to load the file again use FileReader.readAsText. In your "onloadend" handler of the FileReader the method will be called with an event and event.target.result will be your JSON data. Then you'll do a
Nick,只需使用FileWriter.write将您的 JSON 数据保存到磁盘。JSON 无论如何都是基于文本的文件,因此无需设置 mime 类型。当您准备好再次加载文件时,请使用FileReader.readAsText。在 FileReader 的“onloadend”处理程序中,将使用事件调用该方法,而 event.target.result 将是您的 JSON 数据。然后你会做一个
var myJson = JSON.parse(event.target.result);
to turn the text into a JSON object.
将文本转换为 JSON 对象。
回答by Helzgate
(for template or default settings) I just store them in seperate constant files so i don't have to use any special file utility addons or commands, super easy:
(对于模板或默认设置)我只是将它们存储在单独的常量文件中,因此我不必使用任何特殊的文件实用程序插件或命令,超级简单:
(function(){
angular.module('app').constant('settings_json',
{
"name":"settings",
"data":[
{
"set":"globals",
"share_diagnostics":true,
"user_prefs_save_cloud": true
},
{
"set":"user",
"fname":'',
"lname": '',
"telephone": '',
"email": ''
}
]
}
)})();
Then in your app: (after injecting 'settings_json')
然后在您的应用程序中:(在注入“settings_json”之后)
var settings = angular.fromJson(settings_json);