AngularJS errors with JSON parsing

March 16, 2014, 5:17 pm
Author: James Griffiths

If you've been developing with MVVM (Model View - View Model) framework AngularJS chances are you'll have encountered errors with parsing JSON from an AJAX call. Like any good web developer when you inspect the browser console for more information on the nature of the error you'll probably get something along these lines:

Error: JSON Parse error: unterminated string

As far as browsers reporting back JavaScript errors this is probably one of the most helpful as we know exactly what the source of the problem is and where to look (unlike some of the more cryptic errors messages that can sometimes be returned). 

It's all about the formatting

JSON (JavaScript Object Notation) is a lightweight, object-oriented format for storing data that is typically consumed in web applications due to its ease of parsing, reduced file size (in comparison to XML) and JavaScript object based structure.

This makes it perfect for transmitting data from remote servers to websites/applications but, like all data, it has to be properly structured/formatted in order to be successfully parsed.

Common problem #1 - Incorrect structure/syntax

You didn't structure your JSON correctly. Double check that each object declaration is formatted according to the JSON specification and that string content contained within the JSON document is enclosed in double quotes.

Common problem #2 - Entity encoding issues

Where special characters are contained within strings, such as left-single quotes, right-single quotes and ampersands, ensure they are entity encoded to avoid breaking the JSON parser.

Common problem #3 - Hard returns

White space is allowed inside JSON but hard returns aren't. Ensure that your code contains no hard returns.

Common problem #4 - HTML tags

Similar to the previous issue if your string content contains HTML tags ensure there are NO hard returns contained within - this might happen if you have copied and pasted your HTML from a web page or code editor into the JSON file for example.

JSON done right

An easy and convenient way to check if your JSON is formatted correctly is to use the excellent online JSON parser or JSON Lint tool, both of which will immediately report any errors with your code.

An example of properly structured JSON is display below for reference purposes:

[
    {
        "title": "Client website #1",
        "client": "Client Name",
        "summary": "Website summary here",
        "thumbnail": "_assets/_images/_projects/project-thumbnail.jpg",
        "images": [
            {
                "source": "_assets/_images/_projects/image-1.jpg",
                "name": "Home",
                "caption": "Caption #1"
            },
            {
                "source": "_assets/_images/_projects/image-2.jpg",
                "name": "Contact",
                "caption": "Caption #2"
            },
            {
                "source": "_assets/_images/_projects/image-3.jpg",
                "name": "Testimonials",
                "caption": "Caption #3 "
            }
        ],
        "url": "http://www.client website.com",
        "duration": "2 weeks"
    },
    {
        "title": "Client website #2",
        "client": "Client Name",
        "summary": "Website summary here",
        "thumbnail": "_assets/_images/_projects/project-thumbnail.jpg",
        "images": [
            {
                "source": "_assets/_images/_projects/image-1.jpg",
                "name": "Home",
                "caption": "Caption #1"
            },
            {
                "source": "_assets/_images/_projects/image-2.jpg",
                "name": "Contact",
                "caption": "Caption #2"
            },
            {
                "source": "_assets/_images/_projects/image-3.jpg",
                "name": "Testimonials",
                "caption": "Caption #3"
            }
        ],
        "url": "http://www.client website.com ",
        "duration": "2 weeks"
    }
]

A note on minification

If you like to optimise your external JS/CSS assets for reduced HTTP requests/download times you'll obviously be looking to minify and, where appropriate, concatenate related files. When minifying Angular JS scripts it's best practice to preserve dependency injection by using inline bracket notation to represent the injection dependency names as strings.

For example, this:

app.controller("ProjectsCtrl", function($scope, $http){
	$http.get("../App/_assets/_json/projects.json")
    .success(function(data, status, headers, config){
		$scope.projects = data;
	});
});

Would instead, with the use of inline bracket notation, become this:

app.controller("ProjectsCtrl", ["$scope", "$http", function($scope, $http){
	$http.get("../App/_assets/_json/projects.json")
    .success(function(data, status, headers, config){
		$scope.projects = data;
	});
}]);

And your minified Angular JS scripts would work without throwing up dependency injection related errors (and isn't life so much sweeter when things just work?)

Wrapping up

AngularJS is a very powerful and flexible framework for developing JavaScript based applications using the MVVM pattern. Like any technology though you have to understand how it approaches resolving particular problems otherwise you might find yourself banging your head against the wall over seemingly bizarre and 'nonsensical' errors.  If you follow the above rules though you should have no problems with AngularJS consuming your remote JSON file.

Categories

« Return to Posts

Post a comment

All comments are welcome and the rules are simple - be nice and do NOT engage in trolling, spamming, abusiveness or illegal behaviour. If you fail to observe these rules you will be permanently banned from being able to comment.