2012-10-19 55 views
0

可能重複:
How do I reference a javascript object property with a hyphen in it?JavaScript對象 - 不能包含訪問鍵 ' - '

我有以下格式的JSON:

var response1="{" + 
         "\"code\":\"200\"," + 
         "\"requestID\":\"1002\"," + 
         "\"body\":\"[{" + 
         "\\\"author\\\":\\\"sumit\\\"," + 
         "\\\"id\\\":\\\"ABX-002\\\"," + 
         "\\\"title\\\":\\\"How to make Android APK in 2 seconds :)\\\"" + 
         "}," + 
         "" + 
         "{" + 
         "\\\"author\\\":\\\"sumit\\\"," + 
         "\\\"id\\\":\\\"ABX-002\\\"," + 
         "\\\"title\\\":\\\"How to make Android APK in 2 seconds :)\\\"" + 
         "}," + 
         "{"+ 
         "\\\"author\\\":\\\"sumit\\\"," + 
         "\\\"id\\\":\\\"ABX-002\\\"," + 
         "\\\"title\\\":\\\"How to make Android APK in 2 seconds :)\\\"" + 
         "}" + 
         "]\"," + 
         "\"headers\":{\"Server\":\"Apache-Coyote/1.1\"," + 
            "\"Content-Type\":\"text/xml\"," + 
            "\"Content-Length\":\"131\"," + 
            "\"Date\":\"Thu, 06 Sep 2012 09:10:26 GMT\"" + 
            "}" + 
         "}"; 

我想要解析內容類型密鑰。 所以我寫了下面的代碼來解析值:

var jsonResponse = jQuery.parseJSON(response1); 
var contentType = jsonResponse.headers.Content-Type; 

我不能夠得到的Content-Type和Content-Length的值。 任何幫助,將不勝感激。 非常感謝

+0

你爲什麼雙重逃脫身體JSON? – Bergi

+0

嗨Bergi ...我已經作爲字符串對象的響應,所以我已經添加適當的轉義字符,使其成爲一個適當的JSON字符串。 –

回答

5

當鑰匙是不是一個合法的道理,你必須使用一個字符串作爲密鑰,並用數組語法:

var contentType = jsonResponse.headers['Content-Type']; 

注意:這不是一個「JSON解析」的問題,這是標準的Javascript對象訪問規則。

+0

非常感謝Alnitak :) –