我正在开发一个需要将用户数据以 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 并从那里继续。
关于javascript - JSON.parse 在 PhoneGap 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14908717/