将来自 websocket 消息的字符串响应解析为 JSON

Posted

技术标签:

【中文标题】将来自 websocket 消息的字符串响应解析为 JSON【英文标题】:Parse string response from websocket message to JSON 【发布时间】:2018-04-22 07:48:53 【问题描述】:

我收到一个 websocket 消息的消息响应,像这样的字符串

odds.1:["id":1,"marketType":10,"name":"Double chance","status":"HandedOver","specifiers":"","Outcomes":[ ],"id":2,"marketType":11,"name":"平局不下注","status":"HandedOver","specifiers":"","Outcomes":[], "id":3,"marketType":1,"name":"1x2","status":"HandedOver","specifiers":"","Outcomes":[]]

我想将它解析为这样的 json 数组,但不确定如何...

https://gist.github.com/fogofogo/4f984c3c5655b5ee0f1b01840fc01b81

(注意我也需要删除“odds.1”)

我尝试过但没有奏效的方法:

    message.json() JSON.stringify(消息) JSON.parse(消息)

【问题讨论】:

【参考方案1】:

一种快速的方法是,

const a = `odds.1:["id":1,"marketType":10,"name":"Double chance","status":"HandedOver","specifiers":"","Outcomes":[],"id":2,"marketType":11,"name":"Draw no bet","status":"HandedOver","specifiers":"","Outcomes":[],"id":3,"marketType":1,"name":"1x2","status":"HandedOver","specifiers":"","Outcomes":[]]`;

const array = a.split("odds.1:")[1];
const result = JSON.parse(array);
console.log(result);

【讨论】:

很高兴它成功了。尝试使用 Outcomes 数组中的一些元素。【参考方案2】:

您的字符串不是正确的 json。它应该包含在 中,关键赔率 .1 必须用双引号括起来,因为


    "odds .1": [
        "id": 1,
        "marketType": 10,
        "name": "Double chance",
        "status": "HandedOver",
        "specifiers": "",
        "Outcomes": []
    , 
        "id": 2,
        "marketType": 11,
        "name": "Draw no bet",
        "status": "HandedOver",
        "specifiers": "",
        "Outcomes": []
    , 
        "id": 3,
        "marketType": 1,
        "name": "1x2",
        "status": "HandedOver",
        "specifiers": "",
        "Outcomes": []
    ]

【讨论】:

感谢您的回复。它是如何从服务器返回的。我会尝试在ui上修改它。

以上是关于将来自 websocket 消息的字符串响应解析为 JSON的主要内容,如果未能解决你的问题,请参考以下文章

如何确保消息使用 WebSockets 到达目的地?

如何从 Python 中的 websocket 消息增量解析 JSON?

无法解码来自 Websocket 的消息

如何用python解析来自websocket的数据?

如何使用 Tornado 监听来自多个地方的传入 websocket 消息?

带有异步计时器的 Python 异步 websocket 客户端