AngularJS json Filter
Definition and Usage
json
The filter converts a JavaScript object to a JSON string.
This filter is very useful when debugging applications.
A JavaScript object can be any type of JavaScript object.
Related Pages
AngularJS Tutorial:Angular Filters
Instance
Example 1
Display a JavaScript object as a JSON string:
<div ng-app="myApp" ng-controller="jsCtrl"> <h1>Customer:</h1> <pre>{{customer | json}}</pre> </div> <script> var app = angular.module('myApp', []); app.controller('jsCtrl', function($scope) { $scope.customer = { "name" : "Alfreds Futterkiste", "city" : "Berlin", "country" : "Germany" ; }); </script>
Example 2
Ensure that each indentation of the JSON string has 12 spaces:
<div ng-app="myApp" ng-controller="jsCtrl"> <h1>Customer:</h1> <pre>{{customer | json : 12}}</pre> </div> <script> var app = angular.module('myApp', []); app.controller('jsCtrl', function($scope) { $scope.customer = { "name" : "Alfreds Futterkiste", "city" : "Berlin", "country" : "Germany" ; }); </script>
Example 3
JavaScript Object as Array:
<div ng-app="myApp" ng-controller="jsCtrl"> <h1>Carnames:</h1> <pre>{{cars | json}}</pre> </div> <script> var app = angular.module('myApp', []); app.controller('jsCtrl', function($scope) { $scope.cars = ['Audi', 'BMW', 'Ford']; }); </script>
Syntax
{{ object | json : spacing }}
Parameters
Parameters | Description |
---|---|
spacing | Optional. A number, specifying the number of spaces for each indentation. The default value is 2. |