1

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

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Sarang
  • 754
  • 3
  • 9
  • 24

1 Answers1

9

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Thanks @T.J. Crowder Your pre-process string worked for me. I could not fix the source as am receiving it from the third party API. – Sarang Aug 16 '17 at 09:01
  • @Sarang: I'm glad to hear that, but beware, if the source of that string is producing `\x` sequences, it may well do *other* invalid things. The fix really is to fix the source, not to patch up the string after. – T.J. Crowder Aug 16 '17 at 09:02