简体   繁体   中英

Unexpected token u when trying to parse a JSON array from AJAX

I have a PHP script which is used for a POST request which returns (echos) the array:

array(3) {
  ["message"]=>
  string(32) "The item was successfully saved"
  ["newItemId"]=>
  int(9)
  ["newCustomFieldIds"]=>
  string(3) "[9]"
}

My AJAX request:

$.ajax({
        url: 'updateItemDetails.php',
        method: 'post',
        data: {
            ...
        }
    }).done(function(response) {
            console.log(response); //correct
            console.log(response['newCustomFieldIds']); //undefined
            console.log(JSON.parse(response['newCustomFieldIds'])); //unexpected token u
    });

The first console.log produces:

{"message":"The item was successfully saved","newItemId":9,"newCustomFieldIds":"[9]"}

which is as expected. However, the second one gives undefined .

So, when I JSON.parse, I get Uncaught SyntaxError: Unexpected token u ! What I'm trying to do is to get the "[9]" to a real array, ie. [9] .

I don't understand this. newCustomFieldIds definitely exists, because when logging the response , I can see it -- so why doesn't the console.log(response['newCustomFieldIds']) work?

You have to parse response :

JSON.parse(response).newCustomFieldIds

If you want to convert the string "[9]" to an array, you need to call JSON.parse twice:

JSON.parse(JSON.parse(response).newCustomFieldIds)

However, the better solution would be to encode the value of newCustomFieldIds as an array in the first place, ie the JSON should contain "newCustomFieldIds": [9] .


Since you know that response['newCustomFieldIds'] returns undefined , it doesn't make sense to try JSON.parse(response['newCustomFieldIds']) . It's the same as JSON.parse("undefined") , but undefined is not valid JSON.

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