What is the JavaScript Equivalent of print_r in PHP?

What is the JavaScript Equivalent of PHP print_r() function? In other words, how you can “print” a javascript object in a way that’s readable by humans?

Code

You could use JSON.stringify, as following:

The HTML part

Let’s create two links for demo:

1
2
3
<p><a id="print_demo" href="javascript:void(0);">Print object</a></p>
 
<p><a id="pretty_print_demo" href="javascript:void(0);">Pretty Print object</a>

The JAVASCRIPT part

Remark: I use jQuery to handle events, but you can use plain javascript (if you prefer).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<script type="text/javascript">
 
        $(function() {
 
                // create an object
                var person = new Object();
                person.firstname = "John";
                person.lastname = "Doe";
                person.age = "35";
 
                // plain print
                $("#print_demo").click(function() {
                        alert(JSON.stringify(person));
                });
 
                // pretty print
                $("#pretty_print_demo").click(function() {
                        alert(JSON.stringify(person, null, '    '));
                });
 
        });
 
</script>

About Internet Explorer

JSON will not work (by default) on Microsoft Internet Explorer ≤ 9. For a cross browser implementation, get json2.js from https://github.com/douglascrockford/JSON-js and use the following code:

1
2
3
<!--[if lt IE 10]>
<script type="text/javascript" src="json2.js"></script>
<![endif]-->

Another alternative is json3 from https://github.com/bestiejs/json3.

References

From JSON docs

From Mozilla docs