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.
xxxxxxxxxx
1
var object = {"id": 2, "name": "Tom", "age": 25};
2
3
console.log(JSON.stringify(object));
4
/* {"id":2,"name":"Tom","age":25} */
5
6
console.log(JSON.stringify(object, null, 4));
7
/*
8
{
9
"id": 2,
10
"name": "Tom",
11
"age": 25
12
}
13
*/
Note: using
JSON.stringify(userObj)
we convert object to JSON and print to console.
It is possible to convert different types to JSON. Types like: boolean, number, string, object, etc.
Practical example:
xxxxxxxxxx
1
var boolean = true;
2
var number = 2;
3
var string ='Some text inside...';
4
var object = {'id':2,'name':'Tom','age':25};
5
6
function printJSON(entry) {
7
console.log(JSON.stringify(entry));
8
}
9
10
printJSON(boolean); // true
11
printJSON(number); // 2
12
printJSON(string); // Some text inside...
13
printJSON(object); // {"id":2,"name":"Tom","age":25}