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

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)
        }
    }
})

Solution #1:

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().

Respondent: Alfredo EM

Solution #2:

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));
Respondent: Max Voisard

Solution #3:

the values in your object seem to be undefined.
change
var str = {'message': message,'text': text}; to
var str = {message: 'message',text: 'text'};

Respondent: Tal87

Solution #4:

Problem is you’re not parsing a string, you’re parsing an already parsed object.

Respondent: Nalan Madheswaran

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.