简体   繁体   English

JSON.parse在PhoneGap中不起作用

[英]JSON.parse not working in PhoneGap

I'm working on a program that needs to save user data in a file as a JSON format. 我正在开发一个程序,该程序需要将用户数据以JSON格式保存在文件中。 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. 可以很好地将数据保存为JSON,但是当我尝试使用JSON.parse解析存储的JSON时,它不起作用。 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);
}

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. 它以字符串形式返回我的数据,这是字符串形式的返回结果{"status":"true","id":"1","password":"xx"} ,但是当我使用JSON.parse时用我的数据返回未识别的对象。 Here is the part where it uses JSON.parse : 这是它使用JSON.parse的部分:

readUser();
var user = JSON.parse(readUser());
console.log(user);

It won't even run my console.log command with the parsed JSON. 它甚至不会运行带有解析的JSON的console.log命令。

the readUser does not return anything. readUser不返回任何内容。 the content of the file is available in the readAsText callback. 文件的内容在readAsText回调中可用。 you have to json parse the evt.target.result and continue from there. 您必须json解析evt.target.result并从那里继续。

For reading use: 供阅读使用:

jsonVariable = jQuery.parseJSON(evt.target.result);

For writing use: 用于写作:

writer.write(JSON.stringify(propFileJson));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM