简体   繁体   中英

parseJSON error: unexpected character at line 1 column 2 of the JSON data

I have a PHP script like so:

$STL = array();
$filter = array();
$filter['sort_by'] = "date_added";
$filter['sale'] = "F";
$filter['per_page'] = "12";
$STL['filter'] = $filter;
echo json_encode($STL);

This gives the following output:

{"filter":{"sort_by":"date_added","sale":"F","per_page":"12"}}

I am trying to use parseJSON like so:

$.ajax({ 
    url: 'myPHP.php',
    type: 'post',
    data : get_session,
    async: false,
    dataType: 'json',
    success: function(result) {
        var json = $.parseJSON(result);         
    } 
});

But I get the following result:

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

I'm guessing the json string isn't formatted correctly in the PHP. What I got wrong?

If you're using $.parseJSON(result) already on success callback, then remove dataType: 'json', from AJAX properties.. Or use the another way by retaining dataType: 'json' as you expecting JSON already as a result and remove $.parseJSON(result) . Use only either one.

When you specify dataType: 'json' (or jQuery detects a JSON response) then it will automatically parse the JSON for you. If you then attempt to again parse the resulting object you get the error you are seeing. Your result parameter of the success function is already an object you can work with.

Also note that you should never use async: false . It is horrendous practice to use it as it blocks the UI thread until the AJAX request completes. This looks to the user like the browser has crashed. Remove that property from the settings and place all code reliant on the AJAX result in the success handler.

Try this:

$.ajax({ 
    url: 'myPHP.php',
    type: 'post',
    data : get_session,
    dataType: 'json',
    success: function(result) {
        console.log(result);      
    } 
});

the error
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
happens when your json object is not valid. for this case you can check your json by jsonlint ,
but for this case,because of use dataType: 'json' on your ajax request,your output is already is the parsed of josn

{"filter":{"sort_by":"date_added","sale":"F","per_page":"12"}}

$.parseJSON(result) turn string to JSON
your request response is already a valid JSON so, the $.parseJSON(string) return error

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM