chancyWu chancyWu - 1 year ago 130
JSON Question

SyntaxError: Unexpected token & in JSON

I'm using the

to do a GET request, the response is in JSON, but with HTML encoding for some characters, one example is as below, " is encoded with


Also i'm using
, httpErrorsInterceptor will show the error information in
. Since the response JSON is not decoded properly, when try to process it, it will show
SyntaxError: Unexpected token & in JSON
in console. I wonder how can we decode the response
when processing? in

Answer Source

One way to convert html entities to text is to create a dom element , inject the string as html and retrieve it back as text. The DOM parser will do better job of converting than writing your own

var str='{ "description":"invalid", "errorCode":"error.loginInvalid&quot"}'
var JSON = angular.element('<div>').html(str).text();

But example shown is still invalid JSON due to extra quote on last value

working demo with last &quot removed

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download