我运行下面的代码时出现此错误:SyntaxError:JSON.parse:意外字符 data = JSON.parse(data);
当我运行console.log(数据)时;它说数据未定义。
console.log(data);
data = JSON.parse(data);
有人知道如何解决错误问题吗?
答案 0 :(得分:0)
实际上JSON.parse()方法语法是JavaScriptObject JSON.parse(String)
。
这意味着JSON.parse()方法将有效的JSON字符串作为参数,并返回JavascriptObject。如果作为参数传递的String不是有效的JSON String,那么它将引发错误。
因此,首先必须将有效的JSON字符串作为参数传递给JSON.parse()
方法。
答案 1 :(得分:0)
数据未定义。这就是为什么JSON.parse会抛出错误的原因。因此,请调查“数据”的价值是什么。
答案 2 :(得分:0)
如果您可以将空/未定义数据视为空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);
使用data = 'null';
我创建了空的json对象,以便JSON.parse()
不会失败。
答案 3 :(得分:0)
这可能有所帮助:
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);
}
但是如果不了解您的代码,那么很难帮助......您使用的是jQuery吗? ($(...)也可以被其他图书馆使用。)
有关JSON的更多示例,请参阅http://en.wikipedia.org/wiki/JSON,另外还有一个很好的概述。 另外http://www.json.org/