【问题标题】:JSON.parse not working in PhoneGapJSON.parse 在 PhoneGap 中不起作用
【发布时间】:2013-02-01 06:07:45
【问题描述】:

我正在开发一个程序,该程序需要将用户数据保存为 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 命令。

【问题讨论】:

    标签: javascript ios xcode json cordova


    【解决方案1】:

    readUser 不返回任何内容。该文件的内容在 readAsText 回调中可用。你必须 json 解析 evt.target.result 并从那里继续。

    【讨论】:

    • 所以我会使用将我的 evt.target.result 更改为 JSON.parse(evt.target.result) 然后返回 reader.readAsText(file);?
    【解决方案2】:

    阅读用:

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

    写作用:

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

    【讨论】:

      猜你喜欢
      • 2011-11-01
      • 2011-09-14
      • 2013-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-24
      • 2014-10-04
      相关资源
      最近更新 更多