简体   繁体   中英

Jquery - Ajax: SyntaxError: JSON.parse: unexpected character

I am receiving the following valid JSON from my server:

[{"name":"Bubble Witch Saga 2","impressions":10749},{"name":"Grinder","impressions":11284},{"name":"Loovoo","impressions":12336},{"name":"Injustice God Among Us","impressions":12786},{"name":"Bookmyshow","impressions":13182},{"name":"Angry Bird","impressions":15404},{"name":"Flipkart","impressions":16856},{"name":"CNN-IBN","impressions":17230},{"name":"Fore Square","impressions":17595},{"name":"NDTV","impressions":19542},{"name":"Whatsapp","impressions":19976}]

But I keep getting an error in my console saying "JSON.parse: unexpected character." This is my client-side code:

$.ajax({
    'type': 'get',
    'data': {},
    'dataType': 'json',
    'url': 'dashboard/data/'+type,
    'complete': function(data) {
        var top10Value = JSON.parse(data);
        $.each(top10Value, function(key,value){
            console.log(key+" -- "+value);
        });
    }
});

Why am I getting this error?

jQuery is clever enough to parse the response as it is, even if dataType isn't specified.

In your case, it is specified and therefore, it is already parsed and data is the parsed JSON object.

What you are doing is therefore parsing an Object .

Doc says:

dataType : (default: Intelligent Guess (xml, json, script, or html))

Type : String

The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object , in 1.4 script will execute the script, and anything else will be returned as a string). The available types (and the result passed as the first argument to your success callback) are:

data returned already json format only,

    $.ajax({
       'type': 'get',
       'data': {},
       'dataType': 'json',//Return Json Format
       'url': 'dashboard/data/',
       'complete': function(data) {
           //data returned already json format only
           //var top10Value = JSON.parse(data);
           $.each(top10Value, function(key,value){
               console.log(key+" -- "+value);
           });

       }
   });

When you specify dataType : json, result is already parsed in jQuery.

Moreover, complete function argument is returning an object representing the result not the result itself.

That case you should use var top10Value = JSON.parse(data.responseText) ;

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