简体   繁体   English

将字符串响应从 websocket 消息解析为 JSON

[英]Parse string response from websocket message to JSON

I get a message response for a websocket message as a string like this我得到一个 websocket 消息的消息响应作为这样的字符串

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":[]}]赔率.1:[{"id":1,"marketType":10,"name":"双重机会","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":[]}]

And I want to parse it as a json array like this but not sure how ...我想将它解析为这样的 json 数组,但不确定如何...

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

(note I need the 'odds.1' removed too) (注意我也需要删除“odds.1”)

Things I have tried that have not worked:我尝试过但没有奏效的事情:

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

A quick approach would be,一个快速的方法是,

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

Your string is not correct json.您的字符串是不正确的 json。 It should enclose within {} and key odds .1 must be enclosed in double quotes as它应该括在 {} 内,关键赔率 .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": []
    }]
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM