最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Unable to parse JSON string containing unicode hex character - Stack Overflow

programmeradmin2浏览0评论

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

var myparsestring = JSON.parse(mystring);

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

var myparsestring = JSON.parse(mystring);

Error:

Unexpected token x in JSON

Share edited Aug 16, 2017 at 8:40 Rory McCrossan 338k41 gold badges320 silver badges351 bronze badges asked Aug 16, 2017 at 8:38 SarangSarang 7843 gold badges9 silver badges25 bronze badges 3
  • Your JSON isn't encoded properly – Rory McCrossan Commented Aug 16, 2017 at 8:42
  • var mystring = '{"Customers":[{"CustomerCity":"Zaragoza","CustomerFName":"Ana","CustomerAddress":"C/ El Temple, 9 2/\/\xbaB","CustomerCountry":"es"}]}'; var myparsestring = JSON.parse(mystring); – amit wadhwani Commented Aug 16, 2017 at 8:58
  • I have escaped special characters to get it parsed. – amit wadhwani Commented Aug 16, 2017 at 8:59
Add a ment  | 

1 Answer 1

Reset to default 9

That's simply invalid JSON, see the rules for strings on json. There is no \x escape in JSON. The \xbaB should be a unicode escape, \u0baB (note that there must be exactly four hex digits):

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

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

You could try to pre-process the string:

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);

...but really, it would be much better to fix the source of the JSON so it produces valid JSON, and the above is a very naïve fix.

发布评论

评论列表(0)

  1. 暂无评论