Advertisement
Advertisement

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:

Advertisement
<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).

<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>
Advertisement

By Enrico

My greatest passion is technology. I am interested in multiple fields and I have a lot of experience in software design and development. I started professional development when I was 6 years. Today I am a strong full-stack .NET developer (C#, Xamarin, Azure)

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.