chancyWu chancyWu - 5 months ago 37
JSON Question

SyntaxError: Unexpected token & in JSON

I'm using the

$http.get()
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
"


{
"description":"invalid",
"errorCode":"error.loginInvalid"
}


Also i'm using
$httpProvider.interceptors.push('httpErrorsInterceptor');
, httpErrorsInterceptor will show the error information in
responseError
. 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
JSON
when processing? in
$httpProvider
?

Answer

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

Comments