When websocket transmits JSON text, the parse method reports an error

When using websocket to push the JSON data to the front end, websocket needs to convert the JSON data into a string for transmission. In the front end, JavaScript is used to restore the text to a JSON object. Generally, the JSON. Paser () method is used to complete this work. However, in the actual transmission, there is a problem. The JSON. Parse() method always reports an error

Uncaught SyntaxError: Unexpected token ‘ in JSON at position 1
    at JSON.parse (< anonymous>)
    at WebSocket.ws.onmessage ((index):28)

After checking and comparing, it is found that in the process of transferring string by websocket, double quotation marks in string are replaced by single quotation marks, while JSON. Parse() method requires double quotation marks in string. After finding this reason, it is easy to solve it. Before parse conversion, single quotation marks in string are replaced by double quotation marks.

ws.onmessage = function (evt) {
       
        var a = evt.data.replace(/'/g, '"');
        var obj = JSON.parse(a);
        .....
       
       

 
 

Read More: