Skip to content
Advertisement

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

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.

Advertisement

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);
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement