如何将WebSocket返回的特定字符串解析为JSON数组?
Hey there! Let's walk through how to turn that WebSocket message into a usable JSON array. The key issue here is the odds.1: prefix at the start of the string — that's not valid JSON, so we need to strip that first before parsing.
Step 1: Strip the Non-JSON Prefix
Your response string starts with a label (odds.1:) followed by the actual JSON array. To make this robust (in case future messages have similar labels with colons), it's best to split only at the first occurrence of the colon to extract just the JSON part.
Step 2: Parse the JSON String into an Array
Once you've got the pure JSON string, you can use your language's built-in JSON parsing tools to convert it into a native array/object structure.
Let's look at examples for two common languages:
JavaScript Example
// Your raw WebSocket message const rawWsMessage = '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":[]}]'; // Extract the JSON portion (split at first colon) const colonPosition = rawWsMessage.indexOf(':'); const jsonString = rawWsMessage.slice(colonPosition + 1); // Parse into a JSON array try { const oddsArray = JSON.parse(jsonString); // Now you can work with the array! oddsArray.forEach(market => { console.log(`Market Name: ${market.name}, ID: ${market.id}`); }); } catch (err) { console.error('Error parsing JSON:', err); }
Python Example
# Your raw WebSocket message raw_ws_message = '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":[]}]' # Extract the JSON portion (split only once at the first colon) json_string = raw_ws_message.split(':', 1)[1] # Parse into a JSON array import json try: odds_array = json.loads(json_string) # Work with the parsed array for market in odds_array: print(f"Market Name: {market['name']}, ID: {market['id']}") except json.JSONDecodeError as e: print(f"Error parsing JSON: {e}")
Key Notes
- Always wrap the parsing in a try/catch (or try/except in Python) to handle cases where the JSON might be malformed — this prevents your code from crashing if the WebSocket sends an unexpected message.
- Using
indexOf(JS) orsplit(':', 1)(Python) ensures you only remove the prefix, even if the JSON itself contains colons (like in string values).
内容的提问来源于stack exchange,提问作者Jose the hose

