代码之家  ›  专栏  ›  技术社区  ›  Mike Marks

JSON。解析(…)未按预期工作,点语法未工作

  •  0
  • Mike Marks  · 技术社区  · 6 年前

    我想用 JSON.parse(...) 针对JSON字符串,但由于某种原因,当我尝试点(.)访问该对象时,我在JSON中已知存在的节点上得到一个“未定义”的值。不应该 JSON.parse(string) 是否返回对象?

    这是我的密码

    var notificationText = JSON.parse(event.data.text());
    console.log('notificationText Object Stringified: ' + JSON.stringify(notificationText));
    console.log('NotificationText Object Not Stringified: ' + notificationText);
    console.log('NotificationText.Notification Object: ' + notificationText.notification);
    

    这是第一次的控制台输出“ console.log(...) “:

    notificationText Object Stringified: "{\"notification\":{\"body\":\"this is coolfgsdfsfdsfdsdfsdfsfds\",\"title\":\"Whoa\",\"data\":{\"url\":\"http://www.yahoo.com\"},\"requireInteraction\":true}}"
    

    这是第二次的控制台输出“ 安慰日志(…) “:

    NotificationText Object Not Stringified: {"notification":{"body":"this is coolfgsdfsfdsfdsdfsdfsfds","title":"Whoa","data":{"url":"http://www.yahoo.com"},"requireInteraction":true}}
    

    这是第三个”的控制台输出 安慰日志(…) “:

    NotificationText.Notification Object: undefined
    

    以下是我的JSON,格式更易于阅读:

    {
        "notification": {
            "body": "this is coolfgsdfsfdsfdsdfsdfsfds",
            "title": "Whoa",
            "data": {
                "url": "http://www.yahoo.com"
            },
            "requireInteraction": true
        }
    }
    

    我的问题是,为什么我在尝试点语法“notificationText”对象时会得到“未定义”?

    0 回复  |  直到 6 年前
        1
  •  0
  •   Varun Sharma    6 年前

    您正在用字符串连接对象。你应该选择精确的值,比如

    console.log('NotificationText.Notification Object: ' + notificationText.body);
    

    或者,如果仍要按原来的方式打印完整对象,请使用逗号(,)而不是 + 例如:

    console.log('NotificationText.Notification Object: ', notificationText.notification);