AngularJS http.get verify valid json

IHeartAndroid picture IHeartAndroid · Oct 17, 2013 · Viewed 10.9k times · Source

When getting a json from a URL I only want to work with it, when the data is valid.

my approach so far by using JSON:

$http.get(
            'data/mydata.json'
                + "?rand=" + Math.random() * 10000,
            {cache: false}
        )
            .then(function (result) {

                try {
                    var jsonObject = JSON.parse(JSON.stringify(result.data)); // verify that json is valid
                    console.log(jsonObject)

                }
                catch (e) {
                    console.log(e) // gets called when parse didn't work
                }


            })

However before I can do the parsing, angular already fails itself

SyntaxError: Unexpected token { at Object.parse (native) at fromJson (http://code.angularjs.org/1.2.0-rc.2/angular.js:908:14) at $HttpProvider.defaults.defaults.transformResponse (http://code.angularjs.org/1.2.0-rc.2/angular.js:5735:18) at http://code.angularjs.org/1.2.0-rc.2/angular.js:5710:12 at Array.forEach (native) at forEach (http://code.angularjs.org/1.2.0-rc.2/angular.js:224:11) at transformData (http://code.angularjs.org/1.2.0-rc.2/angular.js:5709:3) at transformResponse (http://code.angularjs.org/1.2.0-rc.2/angular.js:6328:17) at wrappedCallback (http://code.angularjs.org/1.2.0-rc.2/angular.js:9106:81) at http://code.angularjs.org/1.2.0-rc.2/angular.js:9192:26 angular.js:7861

How can I prevent angular from throwing this error or how else should I handle verifying the JSON ?

UPDATE: Solution:

$http.get(
// url:
'data/mydata.json'
    + "?rand=" + Math.random() * 10000

,

// config:
{
    cache: false,
    transformResponse: function (data, headersGetter) {
        try {
            var jsonObject = JSON.parse(data); // verify that json is valid
            return jsonObject;
        }
        catch (e) {
            console.log("did not receive a valid Json: " + e)
        }
        return {};
    }
}
)

Answer

Laurent Perrin picture Laurent Perrin · Oct 17, 2013

You can override transformResponse in $http. Check this other answer.