2016-02-13 58 views
0

解析JSON數組我有用於返回一個POST請求(回聲)的陣列中的PHP腳本時:意外標記ü試圖從AJAX

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

我的AJAX請求:

$.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 
    }); 

第一的console.log生產:

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

其是如預期。但是,第二個給出undefined

所以,當我JSON.parse,我得到Uncaught SyntaxError: Unexpected token u!我試圖做的是讓"[9]"真實的數組,即。 [9]

我不明白這一點。 newCustomFieldIds肯定存在,因爲在登錄response時,我可以看到它 - 爲什麼console.log(response['newCustomFieldIds'])不工作?

回答

2

你必須分析response

JSON.parse(response).newCustomFieldIds 

如果你想字符串"[9]"轉換爲數組,你需要調用JSON.parse兩次:

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

然而,更好的解決辦法將首先將newCustomFieldIds的值作爲數組編碼,即JSON應該包含"newCustomFieldIds": [9]


既然你知道response['newCustomFieldIds']回報undefined,它沒有意義的嘗試JSON.parse(response['newCustomFieldIds'])。它與JSON.parse("undefined")相同,但undefined不是有效的JSON。

+0

嗯,現在我得到'意外的令牌a' ..!? (當我解析兩次) –

+0

然後'response'不是你聲稱的值:https://jsfiddle.net/bu63quzb/。一般的解決方案非常簡單:如果您有一個包含JSON的字符串,請調用'JSON.parse'。閱讀[訪問/進程(嵌套)對象,數組或JSON](https://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json)以瞭解更多關於如何訪問對象獲得你想要的價值。 –

+0

http://i.stack.imgur.com/KhGY3.png就是我所看到的! –