Reputation: 784
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
Upvotes: 1
Views: 2773
Reputation: 1074138
That's simply invalid JSON, see the rules for strings on json.org. 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.
Upvotes: 9