简体   繁体   中英

How to strip invalid characters from a JSON $http.get() request?

I'm pulling data from a web-service that I don't control. The results include a backslash before apostrophe's in names (such as O'Donnell). According to JSLint.com the structure of the JSON is valid - except when the response includes the backslashed apostrophes .

I have alerted the provider of the web service. While I am waiting for a response from ReallyBigCo, I wanted to learn more about what's possible on the request end.

Is there a way to strip characters from a JSON object when making an $http.get() request?

I've been searching for solutions to capture the response as a string in order to strip the characters. However, I'm getting an error as soon as the $http.get() function finishes.

This AngularJS code works fine (when the JSON response is valid):

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 display a list of emails in my page using this code when the JSON is valid:

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

Here is an example of working JSON results:

{"findUsers":[
{"email":"aaa.somebody@domain.com"},
{"email":"bbb.somebody@domain.com"},
{"email":"ccc.somebody@domain.com"}
]}

While these JSON results cause an error:

{"findUsers":[
{"email":"aaa.somebody@domain.com"},
{"email":"bbb.somebody@domain.com"},
{"email":"ccc.somebody@domain.com"},
{"email":"ddd.o\'somebody@domain.com"}
]}

The results with apostrophe creates the following error in the console in IE9:

SyntaxError: Invalid characterundefined

I've been searching for solutions to reformat the response, but any JSON results with an apostrophe immediately causes this error. So it doesn't seem possible to use a simple solution such as results.replace(/'/g,""); unless I know how to address the object before the error occurs.

You can do your own transformation of the response and "fix" the data before converting the JSON to an object yourself ( plnkr ):

$scope.testOther = function() {
  $http.get(url, { 
    transformResponse: function(data, headersGetter) {
      // here data is the raw string, you can fix the data here
      // replace first object property name "coord" with "FIXED"
      data = data.replace("coord", "FIXED");
      return angular.fromJson(data);
    }
  }).success(function(data) {
    setValues(data);
  });
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM