![](/img/trans.png)
[英]How to ensure a WebSocket message is JSON string, preventing JSON.parse error?
[英]Parse string response from websocket message to JSON
我得到一個 websocket 消息的消息響應作為這樣的字符串
賠率.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":[]}]
我想將它解析為這樣的 json 數組,但不確定如何...
https://gist.github.com/fogofogo/4f984c3c5655b5ee0f1b01840fc01b81
(注意我也需要刪除“odds.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);
您的字符串是不正確的 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": []
}]
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.