The json filter is used to convert a JavaScript object into a JSON string.
Mostly the json filter is useful for debugging an application.
The binding is automatically converted to JSON when the user using double curly braces {{ }}.
Syntax for json filter in AngularJS:
Parameter value for json filter in AngularJS:
Value
Type
Description
spacing
number
The spacing is an optional value. This is used to specify the number of spaces to use per indentation. The default value of spacing is 2.
Sample coding for json filter in AngularJS:
json Filter in AngularJS
The flowers array item will be displays in json format with “5” space indentation.
Data:
Collection of data has been defined using array for our AngularJS Application.
Logic:
Controller logic for the AngularJS Application.
HTML:
Viewable HTML contents in AngularJS Application.
Code Explanation for json filter in AngularJS
AngularJS is distributed as a JavaScript file, and can be added to a HTML page with a <script> tag.
The AngularJS application is defined by ng-app=" myApp". The application runs inside the <div> tag. It’s also used to define a <div> tag as a root element.
The ng-controller=”jsonCtrl” is an AngularJS directive. It is used to define a controller name as “jsonCtrl”.
The json filter is used to convert a JavaScript object into a JSON string with 5 space indentation.
The angular.module function is used to create an Module. We have passed an empty array to it.
Here we have declared a controller jsonCtrl module using apps.controller() function.
The value of the controller modules is stored in scope object. In AngularJS, $scope is passed as first argument to apps.controller during its constructor definition.
8. Here we have set the value of $scope.flower= [“Lily”, “Rose”, “Jasmine”, “Poppy”] which are to be used to display the {{ floweres | json : 5 }} values in the HTML<div> element.
Sample Output for json filter in AngularJS
The output shows a JavaScript object into a JSON string format with 5 space indentation.