【问题标题】:Parsing messages using Javascript使用 Javascript 解析消息
【发布时间】:2015-02-02 07:33:17
【问题描述】:

我正在通过 web 套接字连接到服务,该服务为发生的某些事件发送消息。

我收到以下格式的消息:

scope("unique_id_01").spot.occupied=false

如何解析此消息以提取值(在本例中为 false)?

注意:
服务 API 文档提到这些消息是可评估的 JavaScript 消息,而不是 JSON 格式。

该服务还发送另一条消息,格式为:

scope("scope_abcd-01").zone.event({"id":"abcd-02","occupied":true,"timestamp":"2015-01-13T09:13:55.644Z", ..otherData});

event(..) 字段中的文本是有效的 json 字符串。为了解析上述事件,我使用了以下代码:

var scope = function (scopeKey) {
    var result = {
        zone: {
            event: function (jsonMsg) {
                console.log("Scope : " + scopeKey + " id : " + jsonMsg.id);
                // use the json
            }
        }
    };
    return result;
};

eval(message received from websocket);

在将它传递给 eval 之前,我还验证了它是有效且真实的响应。

如何解析我收到的两条消息?

【问题讨论】:

  • 这些服务器消息是字符串吗?
  • @Abovestand :是的,这些是字符串

标签: javascript json parsing


【解决方案1】:

使用正则表达式提取相关值:

var messageFromServer = 'scope("unique_id_01").spot.occupied=false';

var matches = /^scope\("(.*)"\)\.spot\.occupied=(.*)$/.exec(messageFromServer);
if(matches){    
    console.log(matches[1]); //'unique_id_01'
    console.log(matches[2]); //'false'   
}

使用捕获组来定位动态内容。这里的所有匹配仍然是字符串 - JSON.parse 你知道的匹配包含有效的 JSON。

【讨论】:

  • 我正在考虑使用 Regex 进行解析,但该服务的文档提到消息是可评估的,因此认为最好不要使用 Regex。有什么建议/意见吗?
  • 服务是否为您提供函数定义?
猜你喜欢
  • 2012-02-24
  • 2012-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-05
  • 2014-12-09
相关资源
最近更新 更多