解析从websocket消息到JSON的字符串响应

时间:2018-04-22 07:48:54

标签: javascript json websocket

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

  

赔率1:[{“id”:1,“marketType”:10,“name”:“Double chance”,“status”:“HandedOver”,“说明者”:“”,“结果”:[ ]},{“id”:2,“marketType”:11,“name”:“不下注”,“状态”:“HandedOver”,“说明者”:“”,“结果”:[]},{ “ID”:3 “marketType”:1, “名称”: “1×2”, “状态”: “HandedOver”, “说明符”: “”, “结果”:[]}]

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

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

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

我尝试过的事情没有奏效:

  1. 的message.json()
  2. JS​​ON.stringify(消息)
  3. JS​​ON.parse(消息)
  4. 任何帮助非常感谢

2 个答案:

答案 0 :(得分:2)

快速的方法是,



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);




答案 1 :(得分:1)

你的字符串不正确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": []
    }]
}