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:
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 3Unexpected token x in JSON
- 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
1 Answer
Reset to default 9That'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.