WEB TUTORIALS
PRACTICE EXAMPLES
HTML REFERENCES
CSS REFERENCES
PHP REFERENCES

How to Pretty-print JSON Using JavaScript

Topic: JavaScript / jQueryPrev|Next

Answer: Use the JavaScript JSON.stringify Method

You can simply use the JSON.stringify() method to pretty-print a JSON object.

Let's try out the following example to understand how it basically works:

// Sample object
var obj = {"name": "Peter", "age": 22, "country": "United States"};

// Pretty printing
var str = JSON.stringify(obj, null, 4); // spacing level = 4

console.log(str);

However, if you have a raw JSON string, you need to convert it to an object first using the JSON.parse() method, before passing it to the JSON.stringify() method, as shown below:

// Sample JSON string
var json = '{"name": "Peter", "age": 22, "country": "United States"}';

// Converting JSON string to object
var obj = JSON.parse(json);

// Pretty printing
var str = JSON.stringify(obj, null, 4); // spacing level = 4

console.log(str);

Related FAQ

Here are some more FAQ related to this topic:

Bootstrap UI Design Templates Property Marvels - A Leading Real Estate Portal for Premium Properties