JavaScript Primer: Working with JSON

The JavaScript Object Notation (JSON) has become the de facto data format for web apps. JSON is simple and easy to work with in JavaScript code, which is why it has become so popular. JSON supports some basic data types, which neatly align with those of JavaScript: Number, String, Boolean, Array, Object, and the special type null.

As a reminder, here is the content of the todo.json file, which contains a simple JSON string:

[{ “action”: “Buy Flowers”, “done”: false },

{ “action”: “Get Shoes”, “done”: false },

{ “action”: “Collect Tickets”, “done”: true },

{ “action”: “Call Joe”, “done”: false }]

The JSON data looks similar to the literal formats used to declare arrays and objects in JavaScript. The only difference is that the property names of the objects are enclosed in quotes.

■ Tip JSON is easy to work with, but you can still get into trouble because JSON libraries encode and decode JSON slightly differently—a problem that can manifest itself when the web app and the servers that support it are written in different programming languages. A common problem is dates, which are hard to work with at the best of times because of all of the regional calendars and notational forms. JSON doesn’t have a native definition for dates, and that gives JSON libraries the kind of latitude that leads to different encoding styles. It is important to test your JSON data thoroughly to ensure that the data is encoded consistently throughout your end-to-end application.

AngularJS makes working with JSON simple. When you request JSON data via Ajax, the response will be parsed automatically into JavaScript objects and passed to the success function, as demonstrated in the previous example when I used the $http.get method to get a JSON file from the web server.

AngularJS supplements this with two methods that explicitly encode and decode JSON: angular.fromJson and angular.toJson. You can see both demonstrated in Listing 5-44.

Listing 5-44. Encoding and Decoding JSON Data in the jsdemo.html File

<!DOCTYPE html>

<html ng-app=”demo”>

<head>

<title>Example</title>

<script src=”angular.js”></script>

<link href=”bootstrap.css” rel=”stylesheet” />

<link href=”bootstrap-theme.css” rel=”stylesheet” />

<script type=”text/javascript”>

var myApp = angular.module(“demo”, []);

myApp.controller(“demoCtrl”, function ($scope, $http) {

$http.get(“todo.json”).success(function (data) {

vax jsonString = angular.toJson(data);

console.log(jsonString);

$scope.todos = angular.fromJson(jsonString);

});

});

</script>

</head>

<body ng-controller=”demoCtrl”>

<div class=”panel”>

<h1>To Do</h1>

<table class=”table”>

<tr><td>Action</td><td>Done</td></tr>

<tr ng-repeat=”item in todos”>

<td>{{item.action}}</td>

<td>{{item.done}}</td>

</tr>

</table>

</div>

</body>

</html>

In this example, I operate on the data object that is passed to the promise success function. This was received as JSON data from the web server and automatically parsed into a JavaScript array by AngularJS. I then call the angular.toJson method to encode the array as JSON again and write it to the console. Finally, I take the JSON that I have created and call the angular.fromJson method to create another JavaScript object, which I use to populate the data model in the AngularJS controller and populate the table element via the ng-repeat directive.

Source: Freeman Adam (2014), Pro AngularJS (Expert’s Voice in Web Development), Apress; 1st ed. edition.

Leave a Reply

Your email address will not be published. Required fields are marked *