Languages
[Edit]
EN

JavaScript - print JSON to the console

5 points
Created by:
Root-ssh
177780

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}

Alternative titles

  1. Print JSON to console in JavaScript
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

JavaScript - JSON

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join