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'
}
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.
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 .
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With