chancyWu
chancyWu

Reputation: 14383

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?

Upvotes: 1

Views: 1200

Answers (2)

chancyWu
chancyWu

Reputation: 14383

The response's content type is text/html;charset=UTF-8, but angularjs will parse as JSON since it starts with { and ends with }, while the content is encoded as HTML, so it would show syntax error when the parser encounters the & character.

One solution is to provide the transformResponse in the $http.config, which is something as below:

$http({
  method: 'get',
  url: yourURL,
  transformResponse: transformResponse
});

function transformResponse(data) {
  var json = angular.element('<div>').html(data).text();
  return JSON.parse(json);
}

If you want to transform all the response, you may add transformResponse to $httpProvider.defaults.transformResponse.

Upvotes: 0

charlietfl
charlietfl

Reputation: 171679

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='{ &quot;description&quot;:&quot;invalid&quot;, &quot;errorCode&quot;:&quot;error.loginInvalid&quot&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

Upvotes: 1

Related Questions