How to convert JavaScript object into JSON string using AngularJS json filter

Waqas Anwar
17 February 2016
3921 Views

If you have a JavaScript object and you want to convert and display it in JSON string format you can use AngularJS built in filter json.

Json filter can be used in HTML templates binding or in JavaScript code to display objects as JSON string on browser console which can be very useful for debugging purpose.

AngularJS

(function () {
   'use strict';

   angular
      .module('app', [])
      .controller('DemoController', DemoController);

      DemoController.$inject = ['$filter']
      function DemoController ($filter){
         var vm = this;
         vm.product = {
            ISBN: "978-1-118-83207-3",
            Title: "Professional AngularJS",
            Price: 45.00,
            Pages: 408,
            Authors: [ "Valeri Karpov", "Diego Netto" ]
         };
      }

      // Use of json filter to display object as JSON string on console 
      console.log($filter("json")(vm.product));

})();

HTML

<!DOCTYPE html>
<html lang="en-US">
   <head></head>
<body ng-app="app">

<div ng-controller="DemoController as vm">
   <pre>
      {{ vm.product | json }}
   </pre>
</div>

<script src="angular.min.js"></script>
<script src="app.js"></script>

</body>
</html>

Output

{
   "ISBN": "978-1-118-83207-3",
   "Title": "Professional AngularJS",
   "Price": 45,
   "Pages": 408,
   "Authors": [
      "Valeri Karpov",
      "Diego Netto"
   ]
}