【问题标题】:Javascript Object - Not able to access keys which contain '-' [duplicate]Javascript 对象 - 无法访问包含“-”的键 [重复]
【发布时间】:2012-10-09 18:18:31
【问题描述】:

可能重复:
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 的值。 任何帮助,将不胜感激。 非常感谢

【问题讨论】:

  • 为什么要对正文 JSON 进行双重转义?
  • 嗨,Bergi ...我已将响应作为字符串对象,因此我添加了适当的转义字符以使其成为适当的 Json 字符串。

标签: javascript jquery json


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-06
    • 2016-05-12
    • 1970-01-01
    • 2022-11-28
    • 1970-01-01
    • 1970-01-01
    • 2019-10-07
    • 1970-01-01
    相关资源
    最近更新 更多