简体   繁体   English

如何将 unicode 字符串转换为 JSON?

[英]How to convert unicode string to JSON?

I want to convert below unicode string to JSON Object.我想将下面的 unicode 字符串转换为 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

decodeURIComponent is out of business here. decodeURIComponent在这里倒闭了。

To use JSON.parse , the format must be correct.要使用JSON.parse ,格式必须正确。

So here, you must first remove line breaks with something like .replace(/(\r\n|\n|\r)/gm,"") .因此,在这里,您必须首先使用.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');然后下一个问题是"PAYMENT" ,这里不能出现双引号,所以可以用.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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM