0

I want to convert below unicode string to JSON Object.

var str = '{"method_title":"Bank. Transfer","instructions":"Account Name: Sriram Me Co.,Ltd.\r\n----------------------------------------------\r\n- Furnin Commercial Bank\r\nAccount: 111-111-111\r\n----------------------------------------------\r\n- LIKSA Bank\r\nAccount: 111-111-111r\n----------------------------------------------\r\n\r\nAfter you have made bank transfer, please kindly visit \"PAYMENT\" to submit your payment detail."}';

below is the approach that I have followed

var myEscapedJSONString = decodeURIComponent(str);
console.log(JSON.parse(myEscapedJSONString));

and I am getting the below error:

Uncaught SyntaxError: Unexpected token in JSON at position 82
Adam Azad
  • 11,171
  • 5
  • 29
  • 70
swamy
  • 49
  • 2
  • 10
  • 1
    Does this answer your question? [How do I handle newlines in JSON?](https://stackoverflow.com/questions/42068/how-do-i-handle-newlines-in-json) – Sergiu Paraschiv Nov 26 '20 at 14:40

1 Answers1

2

decodeURIComponent is out of business here.

To use JSON.parse, the format must be correct.

So here, you must first remove line breaks with something like .replace(/(\r\n|\n|\r)/gm,"").

Then the next problem is "PAYMENT", double quote cannot appears here, so you can remove with .replace(/"PAYMENT"/g, 'PAYMENT');

const str = '{"method_title":"Bank. Transfer","instructions":"Account Name: Sriram Me Co.,Ltd.\r\n----------------------------------------------\r\n- Furnin Commercial Bank\r\nAccount: 111-111-111\r\n----------------------------------------------\r\n- LIKSA Bank\r\nAccount: 111-111-111r\n----------------------------------------------\r\n\r\nAfter you have made bank transfer, please kindly visit \"PAYMENT\" to submit your payment detail."}';

const cleaned = str
  .replace(/(\r\n|\n|\r)/gm, "")
  .replace(/"PAYMENT"/g, 'PAYMENT');

console.log(JSON.parse(cleaned));
Nino Filiu
  • 16,660
  • 11
  • 54
  • 84
farvilain
  • 2,552
  • 2
  • 13
  • 24