angularjs - JSON 中的意外标记 u 位于位置 0

标签 angularjs json local-storage

当我尝试将字符串转换为对象时,我收到错误``:

Unexpected token u in JSON at position 0

服务
setUser : function(aUser){ 
    //sauvegarder User       
    localStorage.setItem('User', JSON.stringify(aUser));
},

getUser : function(){
    //récuperer User      
    return JSON.parse(localStorage.getItem('User'));
}

最佳答案

首先要做的是查看您要解析的内容。我猜你会发现它是 "undefined" ,这是无效的 JSON。您收到 undefined因为您还没有(还)在本地存储中将任何内容保存到该键中。 undefined然后转换为字符串 "undefined"其中JSON.parse无法解析。

我通常在本地存储中存储和检索东西,如下所示:

存储(就像你的一样):

localStorage.setItem("key", JSON.stringify(thing));

检索(这是不同的):
thing = JSON.parse(localStorage.getItem("key") || "null");
if (!thing) {
    // There wasn't one, do whatever is appropriate
}

这样,我总是在解析一些有效的东西。

关于angularjs - JSON 中的意外标记 u 位于位置 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37417012/

相关文章:

angularjs - 如何检测在 Angular Bootstrap 日期选择器中选择日期的时间

javascript - 根据文本检查前面的复选框

javascript - 带有 ng-src 和 ng-repeat 的 if/else 语句

javascript - $watch 检查 AngularJS 范围内定义的变量

Java 解码 JSON

c# - 在 C# 中将 JSON 数组转换为 XML

javascript - jquery中如何将数组json数据转换为特定的json?

javascript - 在Vue js中,如何分配在页面重新加载时不会重置的唯一ID

javascript - Chrome 扩展 : get current page cookie and same to plugin local storage

javascript - Bootstrap 导航栏 #links 正在被 angularjs 更改(或不工作)