Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON

Tags:

I need to append this div to another div , but it give me this error :

SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data

This is my javascript code:

var str = {'message': message,'text': text}; $.ajax({     type: "POST",     url: "api/reply",     data: str,     dataType: "json",     cache: false,     success: function(response)     {         var respons = jQuery.parseJSON(response);         var type = respons.status         if (type == 'success') {             $("<div></div>").html(respons.message).appendTo("#messages");         }         else         {             toastr.error(respons.message)         }     } }) 
like image 262
Ðr Ssamade Avatar asked Jul 16 '16 15:07

Ðr Ssamade


People also ask

How do I fix SyntaxError JSON parse unexpected character at line 1 column 1 of the JSON data?

The "SyntaxError: JSON. parse: unexpected character" error occurs when passing a value that is not a valid JSON string to the JSON. parse method, e.g. a native JavaScript object. To solve the error, make sure to only pass valid JSON strings to the JSON.

What does JSON parse unexpected character at line 1 column 1 of the JSON data mean?

Error parsing JSON: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data. it means that instead of JSON response from LiveAgent API, the client application in browser received something that is not JSON.

How do I fix unexpected token in JSON error?

The "Unexpected token u in JSON at position 0" error occurs when we pass an undefined value to the JSON. parse or $. parseJSON methods. To solve the error, inspect the value you're trying to parse and make sure it's a valid JSON string before parsing it.


2 Answers

Simply change

var respons = jQuery.parseJSON(response);

to

var respons = response;

Explanation:

If the configuration of your AJAX call is having dataType: json you'll get a JavaScript object so it's no longer necessary to use JSON.parse().

like image 119
Alfredo EM Avatar answered Sep 21 '22 18:09

Alfredo EM


This is a hackish and unorthodox way of parsing JSON, but if you still want to use JSON.parse() from an AJAX call or simply on JSON that is already parsed and isn't a string, you can use JSON.stringify() inside it:

var respons = JSON.parse(JSON.stringify(response)); 
like image 31
Max Voisard Avatar answered Sep 22 '22 18:09

Max Voisard