How to stringify js object, so that multiple double quotes are possible when sending it over Socket.io

Tags: , , , ,



Well, i guess the main problem is defined in the title, but some special info is: Im trying to emit events to a socket.io api. For the eventtype part this is working fine, but when using JSON.stringify on the packet body (event data) part (which is supposed to be in this format: "{"msg":"test"}"), it only returns this invalid String: "{"msg":"test"}". I also tried to use single quotes instead of double, but the server doesnt accepts them, so i guess it got a custom parser for these strings.

If anyone has an idea on what to do, i would be really pleased to hear your oppinion.

Answer

You can get your result by double stringifying.

const data = {
  msg: 'test'
};

const stringified = JSON.stringify(data);
const doubleStringified = JSON.stringify(stringified);

console.log(doubleStringified);


Source: stackoverflow