I get this error when Im running the code bellow: SyntaxError: JSON.parse: unexpected character data = JSON.parse(data);
When I run console.log(data); Its says that data is undefined.
console.log(data);
data = JSON.parse(data);
Does somebody know how to fix the error problem?
I get this error when Im running the code bellow: SyntaxError: JSON.parse: unexpected character data = JSON.parse(data);
When I run console.log(data); Its says that data is undefined.
console.log(data);
data = JSON.parse(data);
Does somebody know how to fix the error problem?
Share Improve this question asked Aug 19, 2013 at 8:27 Bruno ChavezBruno Chavez 1933 gold badges5 silver badges15 bronze badges 7- Why don't you show us the problematic code (the string to parse)? Most likely you have whites paces or control characters in your JSON string. – marekful Commented Aug 19, 2013 at 8:29
- We need to see how you are initialising data. – adamjc Commented Aug 19, 2013 at 8:29
- Pls provide more information? – ckv Commented Aug 19, 2013 at 8:29
- @xbonez var data = window.localStorage.getItem(key); – Bruno Chavez Commented Aug 19, 2013 at 8:31
- what is output of window.localStorage.getItem(key); – knightrider Commented Aug 19, 2013 at 8:32
4 Answers
Reset to default 0Actually 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.
Data is undefined. Thats why JSON.parse throws an error. So investigate what is the value for 'data'.
If it is ok for you to treat empty/undefined data as empty json object then try this:
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.
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.)
See http://en.wikipedia/wiki/JSON for more examples of JSON, plus a good overview. Also http://www.json/
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745081453a4610149.html
评论列表(0条)