[英]JSON.parse not working in PhoneGap
我正在开发一个程序,该程序需要将用户数据以JSON格式保存在文件中。 可以很好地将数据保存为JSON,但是当我尝试使用JSON.parse
解析存储的JSON时,它不起作用。 这是我用于存储数据的代码:
function writeUser(data) {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fs){
fs.root.getFile('user.data', {create: true, exclusive: false}, function(fe){
fe.createWriter(function(writer){
//Its converts my data to JSON here
writer.write(JSON.stringify(data));
//It displays this so I knows its been written!
console.log('File written');
}, failwrite);
}, failwrite);
}, failwrite);
}
function failwrite(error) {
console.log(error.code);
}
这是读取我的数据的代码:
function readUser(){
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fs){
fs.root.getFile('user.data', null, function(fe){
fe.file(function(file){
return readAsText(file);
}, failread);
}, failread);
}, failread);
}
function readAsText(file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
console.log(evt.target.result);
};
return reader.readAsText(file);
}
它以字符串形式返回我的数据,这是字符串形式的返回结果{"status":"true","id":"1","password":"xx"}
,但是当我使用JSON.parse时用我的数据返回未识别的对象。 这是它使用JSON.parse
的部分:
readUser();
var user = JSON.parse(readUser());
console.log(user);
它甚至不会运行带有解析的JSON的console.log命令。
readUser不返回任何内容。 文件的内容在readAsText回调中可用。 您必须json解析evt.target.result并从那里继续。
供阅读使用:
jsonVariable = jQuery.parseJSON(evt.target.result);
用于写作:
writer.write(JSON.stringify(propFileJson));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.