Techniques for removing invalid characters from a JSON $http.get() request

While working with data from an external web-service, which I have no control over, I encountered a problem where names containing apostrophes were causing issues due to backslashes being added in the JSON response. JSLint.com confirms that the JSON structure is valid but it breaks when handling these backslashed apostrophes.

I have reached out to the provider of the web service for assistance. In the meantime, as I await a response from ReallyBigCo, I am exploring potential solutions on my end to manipulate the request.

Is there a method to remove characters from a JSON object during an $http.get() request?

I have been researching ways to extract the response as a string in order to clean up the unwanted characters. However, I am encountering errors upon completion of the $http.get() function.

The following AngularJS code functions correctly (for valid JSON responses):

var app = angular.module('app',[]);

app.factory('appresults', function($http) {
  return {
    getAsync: function(callback) {
      var myURL = https://address-to-really-big-co-webservice.com;
      $http.get(myURL).success(callback);
    }
  };
});

app.controller('appcontroller', function($scope, appresults) {
  appresults.getAsync(function(results) {
    $scope.appdata = results.findUsers;
  });
});

I can populate a list of emails on my page using this code when the JSON is valid:

<p ng-repeat="item in appdata">{{item.email}}</p>

Here is an example showcasing successful JSON results:

{"findUsers":[
{"email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f8999999d68b97959d9a979c81b89c9795999196d69b9795">[email protected]</a>"},
{"email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ccaeaeaee2bfa3a1a9aea3a8b58ca8a3a1ada5a2e2afa3a1">[email protected]</a>"},
{"email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a7c4c4c489d4c8cac2c5c8c3dee7c3c8cac6cec989c4c8ca">[email protected]</a>"}
]}

However, the JSON results below trigger an error:

{"findUsers":[
{"email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="315050501f425e5c54535e554871555e5c50585f1f525e5c">[email protected]</a>"},
{"email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="254747470b564a4840474a415c65414a48444c4b0b464a48">[email protected]</a>"},
{"email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4d2e2e2e633e2220282f2229340d2922202c2423632e2220">[email protected]</a>"},
{"email":"ddd.o\'<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="45362a2820272a213c05212a28242c2b6b262a28">[email protected]</a>"}
]}

This issue with apostrophes leads to an error message in the console specifically in IE9:

SyntaxError: Invalid characterundefined

I have been looking into methods for restructuring the response, but any JSON results containing an apostrophe consistently triggers this error. Therefore, employing simple solutions like results.replace(/'/g,""); seems unfeasible unless I find a way to address the object prior to encountering the error.

Answer №1

If you want to customize the response and correct the data before parsing the JSON into an object, you can implement your own transformation function (example):

$scope.customizeData = function() {
  $http.get(apiUrl, { 
    transformResponse: function(responseData, headers) {
      // Here, responseData is the original string data
      // You can make modifications here, like changing property names or values
      responseData = responseData.replace("property", "UPDATED");
      return angular.fromJson(responseData);
    }
  }).success(function(parsedData) {
    updateValues(parsedData);
  });
};

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

Monitoring the flow of data between Angular JS resources and the promise responses

In my application, there is a grid consisting of cells where users can drag and drop images. Whenever an image is dropped onto a cell, a $resource action call is triggered to update the app. My goal is to display a loader in each cell while the update cal ...

Working with Spline Offset Functionality in Three.js

I am working on creating 3D text from font glyphs. While TextGeometry can be used for this purpose, I prefer to manually draw the text because I need to apply an offset on the font splines. Currently, I have the splines with their respective points and I ...

Ensuring the correctness of environment variables in Next.js using Zod

After spending the entire day trying to figure it out, I realize that the solution may be simpler than expected. I am currently using the well-known zod library to validate my environment variables and transform data. However, I keep encountering a persis ...

Transitioning Vue components dynamically

I am facing an issue where the Vue transition is not working as expected for my dynamic components. Check out my code snippet below: <template> <div> <component :is="currentView" transition="fade" transition-mode="out-in">< ...

React JS issue with SVG linearGradient not displaying accurate values

Within my component, I am working with SVG paths and a linearGradient value passed down from the parent component through static data. The properties 'startColor' and 'stopColor' are used to define the gradient colors for each element. ...

What is the best way to execute my mocha fixtures with TypeScript?

I am seeking a cleaner way to close my server connection after each test using ExpressJS, TypeScript, and Mocha. While I know I can manually add the server closing code in each test file like this: this.afterAll(function () { server.close(); ...

Tips for saving an image link when displaying an image in VueJS using the 'require' method

I am currently working on a project that involves displaying Pizza items with their respective images. Each Pizza object is stored in the database along with an imgUrl field. Strangely, the images are not showing up on the page, although I can see the alt ...

`During the useminPrepare process, an error is triggered related to the '

My index.html includes: <!doctype html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]--> <!--[if IE 8]> ...

When attempting to use AJAX to send an object from JavaScript to PHP on the same page, I encountered an issue where, instead of receiving just the object, the entire HTML page was being returned

When I make a POST request, instead of receiving the object as response data, I am getting the entire HTML page back. This is causing me to be unable to retrieve the object in my PHP script. //Here we have an example of the object, not the actual object ...

The remove() method in AJAX function is not functioning as expected

Within a jQuery click event that uses $.post(), I have a .remove() function inside the response callback. Strangely, the alert() seems to function correctly when the code is executed, but the .remove() does not work at all, even though the alert() in the ...

Why is the click event not working in IE8 for JavaScript / jQuery?

There seems to be an issue with the program not functioning properly in IE8 for some users. The website in question is an English course where certain individuals are experiencing difficulty clicking on the correct answers. To view a demonstration of this ...

How to delay form submission in JavaScript/jQuery

I'm having an issue with delaying the submission of a form. When I trigger the submit after the delay, it does not send the post values. Here is my HTML code: <form id="form_anim" name="form" autocomplete="off" action="index.php" method="POST"> ...

What steps should I take to create my own category organizer?

Currently, I am in the process of creating a category organizer for my website. Radio buttons can quickly become overwhelming, while select/option buttons are not very noticeable. After some searching, I came across this unique category organizer and I am ...

Incorporating external CSS links in the metadata of Next.js 13

A recent update in Nextjs 13 introduced a new feature known as Metadata (https://nextjs.org/docs/app/api-reference/functions/generate-metadata), causing the removal of Head.js. Previously, I would import a CSS file using the <Head> tag as shown below ...

Is there a way to have incoming messages automatically align to the left or right based on the sender, without using the float property?

I am currently working on a webpage where I want the messages sent by different users to appear in a yellow conversation window based on who sent them - user 1 or user 2. I want it to mimic the messaging layout commonly seen on phones, distinguishing betwe ...

Filtering rows in JQgrid is made easy after the addition of a new record

Here's the situation I'm facing: Every second, my script adds a new record using the "setInterval" function: $("#grid").jqGrid('addRowData', id, data, 'first').trigger("reloadGrid"); However, when users apply filters while t ...

problem with the visibility of elements in my HTML CSS project

How do I prevent background images from showing when hovering over squares to reveal visible images using CSS? h1 { text-align: center; } .floating-box { float: left; border: 1px solid black; width: 300px; height: 300px; margin: 0px; } div ...

Ways to display an HTML code by utilizing the onclick() function through PHP?

I have a button that looks like this: <input type="submit" name="submit5" class="btn" value="Add Date" onclick="create_date_field()" /> Every time the button is clicked, I want to append the following code inside the <tr> tags. It should be po ...

Encountering a duplicate key error in ExpressJS collection

Whenever I try to create a new event with categories that already exist in my database, such as creating an event with the category "javascript" and then attempting to create another event with categories "javascript, html, css", I encounter the error mess ...

Issue with Async / await: The function is returning true prematurely without waiting for the value to be set in the new state

Currently, I'm in the process of developing a multiple image file upload feature using Firebase and React with Typescript. The issue I am facing revolves around the usage of async/await. In particular, my function uploadFiles is responsible for saving ...