无法解析包含unicode十六进制字符的JSON字符串

时间:2017-08-16 08:38:31

标签: javascript jquery json



var mystring = '{"Customers":[{"CustomerCity":"Zaragoza","CustomerFName":"Ana","CustomerAddress":"C/ El Temple, 9 2\\xbaB","CustomerCountry":"es"}]}';

var myparsestring = JSON.parse(mystring);




错误:

  

JSON中的意外标记x

1 个答案:

答案 0 :(得分:7)

这只是无效的JSON,请参阅字符串on json.org的规则。 JSON中没有\x转义符。 \xbaB应该是unicode转义符\u0baB(请注意,必须有四个十六进制数字):

var mystring ='{"Customers":[{"CustomerCity":"Zaragoza","CustomerFName":"Ana","CustomerAddress":"C/ El Temple, 9 2\\u0baB","CustomerCountry":"es"}]}';

var obj = JSON.parse(mystring);
console.log(obj);

您可以尝试预处理字符串:

mystring = mystring.replace(/\\x([0-9a-f]{1,4})/gi, function(m, c0) {
    return "\\u" + ("0000" + c0).slice(-4);
});

var mystring ='{"Customers":[{"CustomerCity":"Zaragoza","CustomerFName":"Ana","CustomerAddress":"C/ El Temple, 9 2\\xbaB","CustomerCountry":"es"}]}';

// Fixing it
mystring = mystring.replace(/\\x([0-9a-f]{1,4})/gi, function(m, c0) {
    return "\\u" + ("0000" + c0).slice(-4);
});

var obj = JSON.parse(mystring);
console.log(obj);

...但实际上,修复JSON的源代码会更好 ,因此它会生成有效的JSON,而上述内容是一个非常天真的修复。