EN
JavaScript - print JSON to the console
5
points
Hi, today I would like to show you how to print JSON to the console using JavaScript.
// ONLINE-RUNNER:browser;
var object = {"id": 2, "name": "Tom", "age": 25};
console.log(JSON.stringify(object));
/* {"id":2,"name":"Tom","age":25} */
console.log(JSON.stringify(object, null, 4));
/*
{
"id": 2,
"name": "Tom",
"age": 25
}
*/
Note: using
JSON.stringify(userObj)
we convert object to JSON and print to console.
Other type examples
It is possible to convert different types to JSON. Types like: boolean, number, string, object, etc.
Practical example:
// ONLINE-RUNNER:browser;
var boolean = true;
var number = 2;
var string ='Some text inside...';
var object = {'id':2,'name':'Tom','age':25};
function printJSON(entry) {
console.log(JSON.stringify(entry));
}
printJSON(boolean); // true
printJSON(number); // 2
printJSON(string); // Some text inside...
printJSON(object); // {"id":2,"name":"Tom","age":25}