Javascript 对象 - 无法访问包含 '-' 的 key

标签 javascript jquery json

Possible Duplicate:
How do I reference a javascript object property with a hyphen in it?

我有一个以下格式的 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\"" +
                                    "}" +
                        "}";

我想解析 Content-Type Key 。 所以我编写了以下代码来解析该值:

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

我无法获取 Content-Type 和 Content-Length 的值。 任何帮助,将不胜感激。 非常感谢

最佳答案

当key不是合法token时,必须使用字符串作为key并使用数组语法:

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

注意:这不是“JSON 解析”问题,而是标准的 Javascript 对象访问规则。

关于Javascript 对象 - 无法访问包含 '-' 的 key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12969079/

相关文章:

json - 如何在不嵌入的情况下将 JSON 解码添加到外部库类型

javascript - 单选按钮扩展到下拉列表以获得更多选项

javascript - mvc4 :passing locations info to javascript variable for geolocations

python - 具有范围的Elastic Search复合分组

javascript - ng-repeat 不迭代 json 对象

jquery - 使用 fadeIn 使 DIV 平滑显示

javascript - 将数组中的项目设置为空 Javascript

javascript - 无法使用 Three.js

javascript - 页面加载事件中自调用函数的顺序 - javascript/html

javascript - 多层下拉菜单