简体   繁体   中英

Parse string response from websocket message to JSON

I get a message response for a websocket message as a string like this

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":[]}]

And I want to parse it as a json array like this but not sure how ...

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

(note I need the 'odds.1' removed too)

Things I have tried that have not worked:

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

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. It should enclose within {} and key odds .1 must be enclosed in double quotes as

{
    "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": []
    }]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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