【问题标题】:Parse string response from websocket message to JSON将来自 websocket 消息的字符串响应解析为 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”)

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

  1. message.json()
  2. JSON.stringify(消息)
  3. JSON.parse(消息)

【问题讨论】:

    标签: javascript json websocket


    【解决方案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上修改它。
    猜你喜欢
    • 2014-11-12
    • 1970-01-01
    • 1970-01-01
    • 2018-01-27
    • 1970-01-01
    • 1970-01-01
    • 2020-01-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多