Code error: JSON unexpected token "&" encountered

When utilizing the $http.get() method for a GET request, the response is in JSON format, but some characters are HTML encoded. For example, the double quote " is encoded as ".

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

I have also implemented

$httpProvider.interceptors.push('httpErrorsInterceptor');
, where httpErrorsInterceptor displays error information in responseError. However, due to improper decoding of the JSON response, it results in a
SyntaxError: Unexpected token & in JSON
being shown in the console. Is there a way to decode the response JSON correctly during processing within $httpProvider?

Answer №1

If you need to convert HTML entities to text, one effective method is to utilize a DOM element. By injecting the string as HTML and then retrieving it as text, the DOM parser can handle the conversion more efficiently than performing manual coding.

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

However, in the example provided, the JSON remains invalid due to an extra quote on the last value.

Check out a working demo with the unnecessary &quot removed

Answer №2

The content type of the response is set to text/html;charset=UTF-8, however angularjs will interpret it as JSON since it begins with { and ends with }. This can lead to a syntax error when special characters like & are encountered, as the content is actually encoded in HTML.

An effective solution is to utilize the transformResponse property within the $http.config method. Here's an example implementation:

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

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

To apply this transformation globally across all responses, consider adding the transformResponse property to

$httpProvider.defaults.transformResponse
.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to integrate AngularJS into your x-cart platform

Recently, I've been working on x-cart which utilizes the Smarty template engine. My client has requested to integrate angularjs into x-cart, but despite numerous attempts, I have not been successful in implementing it. After researching extensively on ...

The dual-file upload feature of the jQuery ajaxForm plugin

After extensive searching online, I have yet to find an answer to my problem. The issue at hand is that when using the ajaxForm malsup plugin, it submits my files twice. HTML: <form id="gallery" enctype="multipart/form-data" action="/upload-gallery.p ...

Locating the top 3 largest values in an HTML data table and highlighting them in red

Issue Description: I am working with data that displays the electricity consumption of different buildings in HTML tables. There is a possibility that these tables may contain duplicate values. With the use of jQuery, I am seeking a method to identify an ...

jQuery doesn't have the capability to convert this data into JSON format

I have some code that I want to convert into JSON format: var locationData = []; locationData['lat'] = position.coords.latitude; locationData['long'] = position.coords.longitude; locationData['address']['road'] = da ...

Looping through ng-repeats, extracting checked checkbox values in Angular

I am currently dealing with multiple nested ng-repeats in my project, and the third level down consists of a group of checkboxes. Initially, I receive an array of options for these checkboxes, which I handle with the following code snippet: <div class= ...

EaselJS BitmapAnimation has delay when using gotoAndPlay

I have created a requirejs module that enhances the functionality of a BitmapAnimation by allowing it to move around the stage at a specific speed and transition to another looped animation once reaching its destination. The issue I am encountering is a n ...

Is it possible to access the Firebase user object beyond the confines of the Firebase function?

Despite successfully logging users into my application using Google Auth from Firebase, I am facing an issue where the User object does not display on the front end of my application (which utilizes Pug templates). How can I resolve this? The code snippet ...

AngularJS $http is unable to retrieve parameters from the request

Here is an example of AngularJS code: $http({ method: 'POST', url:'/hello/rest/user/test', data: {user: 'aaaaa'} }); And here is the corresponding server-side code: @POST @Path("/test") public Response merge(@Co ...

Finding a quicker route to fulfill a commitment

When dealing with asynchronous behavior in a function, I often find myself creating a deferred and returning a promise. For example: var deferred = $q.defer(); //...some async operation return deferred.promise; However, sometimes I want to skip the async ...

Using PHP to integrate JSON code can provide a seamless way to

I need some help understanding the code snippet below. I'm having trouble grasping all the details. Here's the code: $query = $_SERVER['QUERY_STRING']; $query = explode('&', $_SERVER['QUERY_STRING']); $params = ...

Using LocalStorage in Greasemonkey

I am currently working on developing a Greasemonkey script, but I am encountering difficulties with implementing local storage within it. The method I found to work with local storage in Greasemonkey involves creating another instance of JavaScript using t ...

MeteorJS: Verification of User Email addresses

After sending an email verification to a user, how can I ensure they actually verify their email after clicking on the link sent to their address? I'm aware of this function Accounts.onEmailVerificationLink but I'm unsure of how to implement i ...

When utilizing the Map.get() method in typescript, it may return undefined, which I am effectively managing in my code

I'm attempting to create a mapping of repeated letters using a hashmap and then find the first non-repeated character in a string. Below is the function I've developed for this task: export const firstNonRepeatedFinder = (aString: string): strin ...

Creating a dropdown menu by specifying specific names within an object

I am in the process of setting up a dropdown menu for all 50 states using an object that contains state names as attributes. Here's an example: window.LGMaps.maps.usa = { "paths": [ { "enable": true, "name": "Alaba ...

How to invoke a custom JavaScript function within an ejs template

In an ejs file, I included my own JavaScript function which I intended to use within that file. However, the function is not working as it is declared as undefined. Below is how I declared the function inside the ejs file: //my ejs file <script> ...

Have you ever encountered issues with Promises.all not functioning properly within your vuex store?

I'm currently experiencing an unusual problem. In my Vue project, I have a Vuex store that is divided into different modules. I am trying to utilize Promise.all() to simultaneously execute two independent async Vuex actions in order to benefit from th ...

Unable to see Bootstrap 5.2 Modals in action with documentation demo

Here is an example that I copied and pasted from the documentation on https://getbootstrap.com/docs/5.2/components/modal/: <!-- Button trigger modal --> <button type="button" class="btn btn-primary" data-bs-toggle="modal&q ...

What guidelines need to be followed when incorporating modules into other modules within Angular for the purpose of Dependency Injection?

In my Angular application, I came across the following code in the app.coffee file... app = angular.module 'app', [ 'ngRoute', 'ngResource', 'ui.router', 'app.filters', 'app.services', ...

How can I extract particular combinations from a PHP array?

I have a unique question that is quite specific and despite searching online, I couldn't find an answer. So, I decided to seek advice here. Imagine my webpage has three sliders: one for selecting color options for a square, another for a circle, and ...

Tips for capturing a jQuery trigger in traditional JavaScript

I am trying to trigger an event using jQuery and I want to bind to it in a non-jQuery script. It appears that while I can bind to the event in jQuery using on, I am unable to do so with addEventListener. Check out this jsFiddle for a demonstration: http: ...