我有一个巨大的JSON,它被字符串化成这样的字符串:
"\\u007B\\u0022name\\u0022\\u003A\\u0022T\\u0065st\\u0022}"
我需要JSON.parse以用作对象。您知道解码的方法吗?
我尝试过decodeURIComponent()
,unescape()
,.replace( /\\u/g, "\u" )
的不同变体,但无法将其转换为所需的形式。
您可以使用以下功能将UTF-16转换为文本:
function utf16ToText(s) {
return s.replace(/\\u[0-9a-fA-F]{4}/gi, match => {
return String.fromCharCode(parseInt(match.replace(/\\u/g, ""), 16));
});
}
Demo:]
const r = utf16ToText("\\u007B\\u0022name\\u0022\\u003A\\u0022T\\u0065st\\u0022\\u007d");
console.log("As text: ", r);
const j = JSON.parse(r);
console.log("As JSON: ", j);
console.log("JSON Prop: ", j.name);
function utf16ToText(s) {
return s.replace(/\\u[0-9a-fA-F]{4}/gi, match => {
return String.fromCharCode(parseInt(match.replace(/\\u/g, ""), 16));
});
}
谢谢您的输入。因此,我得到了解决方案:
let a = "\\u007B\\u0022name\\u0022\\u003A\\u0022T\\u0065st\\u0022}"
原始字符串
[let b = '"' + a + '"'
添加“以创建有效的字符串化JSON
let c = JSON.parse(b)
将产生部分解码的字符串(部分是因为某些\ uXXXX字符可以保留在字符串中)
[let solution = JSON.parse(c)
将创建一个具有所有已解码字符的对象]