【发布时间】: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