JSON.parse不工作在PhoneGap [英] JSON.parse not working in PhoneGap
问题描述
我正在开发一个程序,需要将用户数据保存在文件中作为JSON格式。它正在以JSON格式保存我的数据,但是当我尝试使用 JSON.parse
来解析我存储的JSON时,它不工作。
这是我存储数据的代码:
I'm working on a program that needs to save user data in a file as a JSON format. It is doing fine saving my data as JSON but when I try to use JSON.parse
to parse my stored JSON it doesn't work.
Here is my code for storing the data:
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);
}
这里是读取我的数据的代码:
And here is the code that read my data:
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);
}
它返回我的数据作为字符串,这是我得到作为一个string {status:true,id:1,password:xx}
,但是当我使用JSON.parse它返回未识别的对象。这里是它使用的部分 JSON.parse
:
Its returns my data fine as a string, Here is what I get as a string {"status":"true","id":"1","password":"xx"}
, But when I use JSON.parse with my data it returns unidentified object. Here is the part where it uses JSON.parse
:
readUser();
var user = JSON.parse(readUser());
console.log(user);
它甚至不会运行我的console.log命令与解析的JSON。
It won't even run my console.log command with the parsed JSON.
推荐答案
readUser不返回任何内容。该文件的内容在readAsText回调中可用。你必须json解析evt.target.result并从那里继续。
the readUser does not return anything. the content of the file is available in the readAsText callback. you have to json parse the evt.target.result and continue from there.
这篇关于JSON.parse不工作在PhoneGap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!