javascript 如何修复错误:JSON.parse:意外字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18309398/
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
How to fix error: JSON.parse: unexpected character?
提问by Bruno Chavez
I get this error when Im running the code bellow: SyntaxError: JSON.parse: unexpected character data = JSON.parse(data);
当我运行以下代码时出现此错误: SyntaxError: JSON.parse: unexpected character data = JSON.parse(data);
When I run console.log(data); Its says that data is undefined.
当我运行 console.log(data); 它说数据是未定义的。
console.log(data);
data = JSON.parse(data);
Does somebody know how to fix the error problem?
有人知道如何解决错误问题吗?
回答by Azeez
Actually the JSON.parse() method syntax is JavaScriptObject JSON.parse(String)
.
It means the JSON.parse() method takes a valid JSON string as argument and it returns a JavascriptObject. If the String, which is passed as the argument is not a valid JSON String then it will throw an error.
So,first you have to pass a valid JSON String as argument to the JSON.parse()
method.
实际上 JSON.parse() 方法的语法是JavaScriptObject JSON.parse(String)
. 这意味着 JSON.parse() 方法将有效的 JSON 字符串作为参数,并返回一个 JavascriptObject。如果作为参数传递的字符串不是有效的 JSON 字符串,那么它将抛出错误。因此,首先您必须将有效的 JSON 字符串作为参数传递给该JSON.parse()
方法。
回答by Manikandan
Data is undefined. Thats why JSON.parse throws an error. So investigate what is the value for 'data'.
数据未定义。这就是 JSON.parse 抛出错误的原因。因此,调查“数据”的价值是什么。
回答by Aziz Shaikh
If it is ok for you to treat empty/undefined data as empty json object then try this:
如果您可以将空/未定义数据视为空 json 对象,请尝试以下操作:
var key = $(this).attr("track_id");
$("#track_info div[data-role=header] h1").text(key);
var data = window.localStorage.getItem(key);
if (data == undefined || data == null || data == "")
{
data = 'null';
}
else
{
console.log(data);
}
data = JSON.parse(data);
console.log(data);
Using data = 'null';
I have created null json object so that JSON.parse()
doesn't fail.
使用data = 'null';
我创建了 null json 对象,这样JSON.parse()
就不会失败。
回答by Mesh
This may help:
这可能有帮助:
var key = $(this).attr("track_id");
$("#track_info div[data-role=header] h1").text(key);
var data = window.localStorage.getItem(key);
console.log(data); /* The output here may indicate the problem */
/* valid JSON should be a string like
"{ \"propName\":\"propValue\" , ...}"
*/
try{
data = JSON.parse(data);
}
catch(e){
console.log(e);
}
But without knowing more about your code it's very difficult to help...are you using jQuery? ( $(...) can be used by other libraries too.)
但是,如果不了解更多关于您的代码的信息,就很难提供帮助……您在使用 jQuery 吗?( $(...) 也可以被其他库使用。)
See http://en.wikipedia.org/wiki/JSONfor more examples of JSON, plus a good overview. Also http://www.json.org/
请参阅http://en.wikipedia.org/wiki/JSON以获取更多 JSON 示例以及一个很好的概述。还有http://www.json.org/