Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript log json object with pretty format

I'm using a lot console.log for debugging purpose. When I log long objects, it is difficult to read the complete object. Is there a console.pretty or something to print the data in a pretty way?

Actual (logs inline):
{data:'data',data1:'data1'}

Expect:

{
  data:'data',
  data1:'data1'
}
like image 342
Alvaro Joao Avatar asked Oct 12 '15 03:10

Alvaro Joao


People also ask

How do I make my JSON response pretty?

Use JSON. stringify(obj) method to convert JavaScript objects into strings and display it. Use JSON. stringify(obj, replacer, space) method to convert JavaScript objects into strings in pretty format.

What is pretty JSON format?

Pretty printing is a form of stylistic formatting including indentation and colouring. JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write and for machines to parse and generate. The official Internet media type for JSON is application/json .

How show JSON data Pretty in HTML?

use a <pre> tag to JavaScript pretty prints JSON in HTML. The <pre> need id to show data on it. Where pre tells the browser engine that the content inside is pre-formatted and can be displayed without any modification. To convert it to JSON and pretty print use stringify method.


1 Answers

You can use JSON.stringify.

The third parameter passed will be the number of spaces to indent the members.

var obj = {
  data: 'data',
  data1: 'data1'
};

console.log(JSON.stringify(obj, 0, 2));

If you need this more often, you can also define a function on window object

// Define on global window object
window.console.prettyPrint = function() {
  // Loop over arguments, so any number of objects can be passed
  for (var i = 0; i < arguments.length; i++) {
    console.log(JSON.stringify(arguments[i], 0, 2));
  }
};

var obj = {
  data: 'data',
  data1: 'data1'
};

var myObj = {
  hello: 'World!'
};

console.prettyPrint(obj, myObj);
like image 168
Tushar Avatar answered Sep 29 '22 08:09

Tushar