I am having a problem parsing simple JSON strings. I have checked them on JSONLint and it shows that they are valid. But when I try to parse them using either JSON.parse
or the jQuery alternative it gives me the error unexpected token o
:
<!doctype HTML>
<html>
<head>
</head>
<body>
<script type="text/javascript">
var cur_ques_details ={"ques_id":15,"ques_title":"jlkjlkjlkjljl"};
var ques_list = JSON.parse(cur_ques_details);
document.write(ques_list['ques_title']);
</script>
</body>
</html>
Note: I'm encoding my strings using json_encode()
in PHP.
This question is related to
javascript
json
cur_ques_details
is already a JS object, you don't need to parse it
Using JSON.stringify(data);
:
$.ajax({
url: ...
success:function(data){
JSON.stringify(data); //to string
alert(data.you_value); //to view you pop up
}
});
Response is already parsed, you don't need to parse it again. if you parse it again it will give you "unexpected token o
". if you need to get it as string, you could use JSON.stringify()
Try parse so:
var yourval = jQuery.parseJSON(JSON.stringify(data));
I had the same problem when I submitted data using jQuery AJAX:
$.ajax({
url:...
success:function(data){
//server response's data is JSON
//I use jQuery's parseJSON method
$.parseJSON(data);//it's ERROR
}
});
If the response is JSON, and you use this method, the data you get is a JavaScript object, but if you use dataType:"text"
, data is a JSON string. Then the use of $.parseJSON
is okay.
The source of your error, however, is that you need to place the full JSON string in quotes. The following will fix your sample:
<!doctype HTML>
<html>
<head>
</head>
<body>
<script type="text/javascript">
var cur_ques_details ='{"ques_id":"15","ques_title":"jlkjlkjlkjljl"}';
var ques_list = JSON.parse(cur_ques_details);
document.write(ques_list['ques_title']);
</script>
</body>
</html>
As the other respondents have mentioned, the object is already parsed into a JS object so you don't need to parse it. To demonstrate how to accomplish the same thing without parsing, you can do the following:
<!doctype HTML>
<html>
<head>
</head>
<body>
<script type="text/javascript">
var cur_ques_details ={"ques_id":"15","ques_title":"jlkjlkjlkjljl"};
document.write(cur_ques_details.ques_title);
</script>
</body>
</html>
I was seeing this unexpected token o
error because my (incomplete) code had run previously (live reload!) and set the particular keyed local storage value to [object Object]
instead of {}
. It wasn't until I changed keys, that things started working as expected. Alternatively, you can follow these instructions to delete the incorrectly set localStorage value.
Source: Stackoverflow.com