JSON 中的意外标记 u 位于位置 0
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37417012/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Unexpected token u in JSON at position 0
提问by nevergiveup
when I'm try to convert string to object I get error ``:
当我尝试将字符串转换为对象时,我收到错误``:
Unexpected token u in JSON at position 0
Service
服务
setUser : function(aUser){
//sauvegarder User
localStorage.setItem('User', JSON.stringify(aUser));
},
getUser : function(){
//récuperer User
return JSON.parse(localStorage.getItem('User'));
}
回答by T.J. Crowder
The first thing to do is to look at what you're trying to parse. My guess is that you'll find it's "undefined", which is invalid JSON. You're getting undefinedbecause you haven't (yet) saved anything to that key in local storage. undefinedis then converted to the string "undefined"which JSON.parsecan't parse.
首先要做的是查看您要解析的内容。我猜你会发现它是"undefined",这是无效的 JSON。你得到的undefined是因为你还没有(还)在本地存储中将任何内容保存到该键中。undefined然后转换成字符串"undefined",其JSON.parse无法解析。
I usually store and retrieve things in local storage like this:
我通常在本地存储中存储和检索东西,如下所示:
Storing (just like yours):
存储(就像你的一样):
localStorage.setItem("key", JSON.stringify(thing));
Retrieving (this is different):
检索(这是不同的):
thing = JSON.parse(localStorage.getItem("key") || "null");
if (!thing) {
// There wasn't one, do whatever is appropriate
}
That way, I'm always parsing something valid.
这样,我总是在解析一些有效的东西。
回答by Abhishek Dadhich
You are getting this error because you are not returning the response as a JSON string while your browser is expecting a JSON string to parse. Hence it is taking the first letter of your response string and throwing an error.
您收到此错误是因为您没有将响应作为 JSON 字符串返回,而浏览器需要解析 JSON 字符串。因此,它采用响应字符串的第一个字母并抛出错误。
You can verify it by going to the networking tab of your browser's Dev tools and viewing the response.
您可以通过转到浏览器开发工具的网络选项卡并查看响应来验证它。
To resolve this issue, you can use the code below in your http request.
要解决此问题,您可以在 http 请求中使用以下代码。
var promiz = $http.post(url, data, {
transformRequest: angular.identity,
transformResponse: angular.identity,
headers: {
'Content-Type': undefined
}
});
Hope this helps!
希望这可以帮助!
回答by Aarchie
I was also getting the same error. The problem was the response I was getting from HTTP Get Request was not in JSON format, Instead it was plain text.
我也遇到了同样的错误。问题是我从 HTTP Get Request 得到的响应不是 JSON 格式,而是纯文本。
this.BASE_URL = "my URL";
public getDocument() {
return this.http.get(this.BASE_URL)
.map((res: Response) => res.json())
.catch((error: any) => Observable.throw(error.json().error || 'Server error'));
}
So, the JSON Parser was throwing an error.
所以,JSON 解析器抛出了一个错误。
When I map it into plain text like this:
当我将其映射为这样的纯文本时:
.map((res: Response) => res.text());
It works.
有用。

