Hello there.
I’ve been retrieving bits information from the pubsub for a while now, and until now I had no problems in dealing with the malformed JSON response.
But now that subscriptions have been introduced to the pubsub I have a hard time dealing with the responses.
Let me give an example.
This is the code I currently have which deals with bits:
psSocket.onmessage = function(data) {
data = JSON.parse(data.data.replace(/\\/g, '').replace('","message":"{"data"', '","message":{"data"').replace('"}"}}', '"}}}'));
switch(data.type) {
case "RESPONSE": {
if(debug_bits)
consoleLog('BITS SOCKET RESPONSE:'), consoleLog(data);
} break;
case "MESSAGE": {
consoleLog(data);
switch(data.data.topic) {
case 'channel-bits-events-v1.' + window.channel_id: {
if(debug_bits)
consoleLog('BITS SOCKET RETRIEVE: x' + data.data.message.data.bits_used + ' FROM ' + data.data.message.data.user_name + ' WITH MESSAGE: \'' + data.data.message.data.chat_message + '\'');
} break;
case 'channel-subscribe-events-v1.' + window.channel_id: {
if(debug_subscribers)
consoleLog('SUBSCRIBER SOCKET RETRIEVE: x' + data.data.message.months + ' FROM ' + data.data.message.user_name + ' WITH MESSAGE: \'' + data.data.message.sub_message.message + '\'');
} break;
}
} break;
}
};
And this is the usual response you get when someone send bits:
{"type":"MESSAGE","data":{"topic":"channel-bitsevents.XXXXX","message":"{\"user_name\":\"TestUsername12345\",\"channel_name\":\"TestChannel12345\",\"user_id\":\"TestUserID12345\",\"channel_id\":\"TestChannelID12345\",\"time\":\"2017-06-3T12:00:00.000Z\",\"chat_message\":\"cheer1 Test message.\",\"bits_used\":1,\"total_bits_used\":1,\"context\":\"cheer\"}"}}
The problem I’m speaking of is the fact that I have to use this:
JSON.parse(data.data.replace(/\\/g, '').replace('","message":"{"data"', '","message":{"data"').replace('"}"}}', '"}}}'));
to avoid JSON.parse giving away this error:
jQuery.Deferred exception: Unexpected token u in JSON at position 74 SyntaxError: Unexpected token u in JSON at position 74
Until now I was able to avoid that problem by using:
.replace('","message":"{"data"', '","message":{"data"').replace('"}"}}', '"}}}'));
But now, since subscriptions have been introduced to the pubsub, and they are PROPERLY formatted, I have no way of interpreting a malformed message one way, and a properly formatted message another way.
I would like to kindly ask for the bits response messages to be formatted properly, because JSON.parse throws an error as soon as I try to parse the whole response.