Pretty-printing is implemented natively in JSON.stringify(). The third argument enables pretty printing and sets the spacing to use:

var str = JSON.stringify(obj, null, 2); // spacing level = 2

If you need syntax highlighting, you might use some regex magic like so:

function syntaxHighlight(json) {
    if (typeof json != 'string') {
         json = JSON.stringify(json, undefined, 2);
    }
    json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
    return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
        var cls = 'number';
        if (/^"/.test(match)) {
            if (/:$/.test(match)) {
                cls = 'key';
            } else {
                cls = 'string';
            }
        } else if (/true|false/.test(match)) {
            cls = 'boolean';
        } else if (/null/.test(match)) {
            cls = 'null';
        }
        return '<span class="' + cls + '">' + match + '</span>';
    });
}

See in action here: jsfiddle

Or a full snippet provided below:

function output(inp) {
    document.body.appendChild(document.createElement('pre')).innerHTML = inp;
}

function syntaxHighlight(json) {
    json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
    return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
        var cls = 'number';
        if (/^"/.test(match)) {
            if (/:$/.test(match)) {
                cls = 'key';
            } else {
                cls = 'string';
            }
        } else if (/true|false/.test(match)) {
            cls = 'boolean';
        } else if (/null/.test(match)) {
            cls = 'null';
        }
        return '<span class="' + cls + '">' + match + '</span>';
    });
}

var obj = {a:1, 'b':'foo', c:[false,'false',null, 'null', {d:{e:1.3e5,f:'1.3e5'}}]};
var str = JSON.stringify(obj, undefined, 4);

output(str);
output(syntaxHighlight(str));
pre {outline: 1px solid #ccc; padding: 5px; margin: 5px; }
.string { color: green; }
.number { color: darkorange; }
.boolean { color: blue; }
.null { color: magenta; }
.key { color: red; }

Answer from user123444555621 on Stack Overflow
Top answer
1 of 16
6932

Pretty-printing is implemented natively in JSON.stringify(). The third argument enables pretty printing and sets the spacing to use:

var str = JSON.stringify(obj, null, 2); // spacing level = 2

If you need syntax highlighting, you might use some regex magic like so:

function syntaxHighlight(json) {
    if (typeof json != 'string') {
         json = JSON.stringify(json, undefined, 2);
    }
    json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
    return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
        var cls = 'number';
        if (/^"/.test(match)) {
            if (/:$/.test(match)) {
                cls = 'key';
            } else {
                cls = 'string';
            }
        } else if (/true|false/.test(match)) {
            cls = 'boolean';
        } else if (/null/.test(match)) {
            cls = 'null';
        }
        return '<span class="' + cls + '">' + match + '</span>';
    });
}

See in action here: jsfiddle

Or a full snippet provided below:

function output(inp) {
    document.body.appendChild(document.createElement('pre')).innerHTML = inp;
}

function syntaxHighlight(json) {
    json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
    return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
        var cls = 'number';
        if (/^"/.test(match)) {
            if (/:$/.test(match)) {
                cls = 'key';
            } else {
                cls = 'string';
            }
        } else if (/true|false/.test(match)) {
            cls = 'boolean';
        } else if (/null/.test(match)) {
            cls = 'null';
        }
        return '<span class="' + cls + '">' + match + '</span>';
    });
}

var obj = {a:1, 'b':'foo', c:[false,'false',null, 'null', {d:{e:1.3e5,f:'1.3e5'}}]};
var str = JSON.stringify(obj, undefined, 4);

output(str);
output(syntaxHighlight(str));
pre {outline: 1px solid #ccc; padding: 5px; margin: 5px; }
.string { color: green; }
.number { color: darkorange; }
.boolean { color: blue; }
.null { color: magenta; }
.key { color: red; }

2 of 16
441

User Pumbaa80's answer is great if you have an object you want pretty printed. If you're starting from a valid JSON string that you want to pretty printed, you need to convert it to an object first:

var jsonString = '{"some":"json"}';
var jsonPretty = JSON.stringify(JSON.parse(jsonString),null,2);  

This builds a JSON object from the string, and then converts it back to a string using JSON stringify's pretty print.

🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › JSON › stringify
JSON.stringify() - JavaScript | MDN
The JSON.stringify() static method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.
🌐
ReqBin
reqbin.com › code › javascript › ounkkzpp › javascript-pretty-print-json-example
How do I pretty print JSON in JavaScript?
JavaScript has a built-in JSON.stringify(obj, replacer, space) method to convert objects to JSON and pretty-print the generated JSON string.
🌐
W3Schools
w3schools.com › js › js_json_stringify.asp
JSON.stringify()
Use the JavaScript function JSON.stringify() to convert it into a string. ... The result will be a string following the JSON notation.
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-pretty-print-json-string-in-javascript
How to Pretty Print JSON String in JavaScript? - GeeksforGeeks
July 12, 2025 - const obj = { name: "Rahul", age: 30, city: "Mumbai" }; const pretty = JSON.stringify(obj, null, 2); console.log(pretty); ... The JSON object to stringify. A replacer function (optional).
🌐
W3Resource
w3resource.com › JSON › snippets › json-stringify-pretty.php
JSON.stringify for Pretty Print
However, it has an optional third argument called space that allows "pretty-printing" the JSON output by adding indentation and line breaks, making the JSON string more readable. ... replacer (optional): A function or array used to modify or ...
🌐
ServiceNow Community
servicenow.com › community › developer-articles › json-stringify-making-json-look-pretty-and-perfect › ta-p › 2534944
JSON.stringify() - Making JSON Look Pretty and Per... - ServiceNow Community
December 9, 2025 - But wait, there's more! JSON.stringify() has many use cases beyond just making your code look pretty. For instance, if you're working with APIs, you can use it to convert your JSON object into a string that can be sent as a request.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Object › toString
Object.prototype.toString() - JavaScript | MDN
... class Dog { constructor(name, ... code in place, any time an instance of Dog is used in a string context, JavaScript automatically calls the toString() method....
🌐
Attacomsian
attacomsian.com › blog › javascript-pretty-print-json
How to pretty-print a JSON object with JavaScript
October 15, 2022 - Only the JSON object is required. The remaining two parameters are optional. To improve the JSON string readability, pass a number as the 3rd argument representing the total white spaces to insert. The white space count must be between 0 and 10: const obj = { name: 'Atta', profession: 'Software Engineer', country: 'PK', skills: ['Java', 'Spring Boot', 'Node.js', 'JavaScript'] } // serialize JSON object const str = JSON.stringify(obj, null, 4) // print JSON string console.log(str)
Find elsewhere
🌐
EDUCBA
educba.com › home › software development › software development tutorials › javascript tutorial › json stringify pretty
JSON Stringify Pretty | Examples of JSON Stringify Pretty in Javascript
April 12, 2023 - Also illustrated example for JSON Pretty in JS and Python. Pretty can prettify size, color, the indentation of the JSON output. JSON Stringifies the object to string and prettifies the JSON data as per user requirements.
Address   Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
🌐
GitHub
github.com › Chris-Baker › pretty-print-object
GitHub - Chris-Baker/pretty-print-object: Stringify an object/array like JSON.stringify just without all the double-quotes
Useful for when you want to get the string representation of an object in a formatted way. It also handles circular references and lets you specify quote type. ... import { prettyPrint } from '@base2/pretty-print-object'; const obj = { foo: 'bar', 'arr': [1, 2, 3], nested: { hello: "world" } }; const pretty = prettyPrint(obj, { indent: ' ', singleQuotes: false }); console.log(pretty); /* { foo: "bar", arr: [ 1, 2, 3 ], nested: { hello: "world" } } */
Starred by 5 users
Forked by 3 users
Languages   TypeScript 88.0% | JavaScript 12.0%
🌐
JSONBin
jsonbin.io › blog › 1 › how-to-pretty-print-a-json-object-with-javascript
How to pretty-print a JSON object with JavaScript - JSONBin.io
Copyconst myObj = { "people": [ { "name": "Mark Vande Hei", "craft": "ISS" }, { "name": "Oleg Novitskiy", "craft": "ISS" }, { "name": "Pyotr Dubrov", "craft": "ISS" } ] }; // serialize myObj const str = JSON.stringify(myObj, null, 2); // pretty print console.log(str); The above code will pretty-print the JSON object as a string like:
🌐
Delft Stack
delftstack.com › home › howto › javascript › json stringify pretty
How to Pretty Print JSON in JavaScript | Delft Stack
March 11, 2025 - One of the most straightforward ways to pretty print JSON in JavaScript is by using the JSON.stringify() method. This method converts a JavaScript object into a JSON string, and it can also take additional parameters to format the output.
🌐
DEV Community
dev.to › speaklouder › how-to-pretty-json-output-using-javascript-27k6
How to Pretty JSON Output using JavaScript - DEV Community
October 3, 2023 - How can we use JavaScript to make our JSON output look good? The key tool we'll use is the JSON.stringify() method, which provides a simple way to format JSON. ... const jsonData = { name: "SpeakLouder", age: 24, city: "India" }; const prettyJSON ...
🌐
DhiWise
dhiwise.com › post › javascript-essentials-detailed-exploration-of-json-stringify
Exploring JSON Stringify: An In-Depth Exploration
September 29, 2023 - This method is commonly used to send data from the client side to a web server in a string format. ... The JSON.stringify() method also allows us to pretty print JSON data using the space parameter for indentation, making the output more readable.
🌐
ZetCode
zetcode.com › javascript › json-pretty-print
JavaScript JSON Pretty Print - Formatting JSON Data
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <script> fetch('https://jsonplaceholder.typicode.com/todos/1') .then(response => response.json()) .then(json => document.body.appendChild(document.createElement('pre')).innerHTML = JSON.stringify(json, null, 4)); </script> </body> </html> We fetch one todo object from the testing website. ... In this article we have prettified JSON output in JavaScript.
🌐
Coding With Spike!
codingwithspike.wordpress.com › 2016 › 11 › 08 › pretty-printing-javascript-objects
Pretty-printing JavaScript objects with JSON.stringify | Coding With Spike!
November 8, 2016 - By passing a number, that many spaces will be used to indent each level of properties. ... var user = { first: 'John', last: 'Doe', age: 42 }; // plain console log console.log(JSON.stringify(user, undefined, 2)); // or with interpolation: console.log(`User: ${JSON.stringify(user, undefined, 2)}`); ... Much nicer! ... Like Loading... ... CodingWithSpike is Jeff Valore. A professional software engineer, focused on JavaScript and Web Development
🌐
The Code Barbarian
thecodebarbarian.com › pretty-json-stringify-output.html
Pretty `JSON.stringify()` Output in JavaScript
const app = express(); app.use(express.text({ type: '*/*' })); app.post('*', (req, res) => { console.log(req.body); res.end(req.body); }); await app.listen(3000); // Make a test request const axios = require('axios'); const obj = { name: 'Jean-Luc Picard', rank: 'Captain', ship: 'Enterprise D' }; const res = await axios.post('http://localhost:3000', obj, { transformRequest: data => JSON.stringify(data, null, 2), // Send pretty formatted JSON transformResponse: body => body }); // { // "name": "Jean-Luc Picard", // "rank": "Captain", // "ship": "Enterprise D" // } console.log(res.data); The prettyjson npm package is a great way to add neat color formatting to your JSON output.
Top answer
1 of 2
3

I am prejudiced against variables named data.

You need to escape literal ", \, and \n characters in quoted strings. It's good form to do tabs too.

Using a dispatch table for types (instead of if/else) makes it easy to handle all the types.

Instead of passing tab up and down the call stack, wrap the calls in a function that indents a block of text. Nested traverse will be nested in indent too and get indented the right number of times.

Instead of checking whether you're at the end of a delimited list (to decide whether to add a delimiter), use arr.join(delimiter). It puts delimiters on inner boundaries only.

Array(n).fill(' ').join(''); is the same as ' '.repeat(n).

It would be nice to omit the quotes on property names that don't need them. Doing this perfectly happens to be really laborious—the regex is 11 kilobytes long!! It's manageable if we limit the exceptions to 7-bit ASCII, which is probably a good idea anyway.

function prettyPrint(obj) {
    const stringify = {
        "undefined": x => "undefined",
        "boolean":   x => x.toString(),
        "number":    x => x,
        "string":    x => enquote(x),
        "object":    x => traverse(x),
        "function":  x => x.toString(),
        "symbol":    x => x.toString()
    },
    indent = s => s.replace(/^/mg, "  "),
    keywords = `do if in for let new try var case else enum eval null this true 
            void with await break catch class const false super throw while 
            yield delete export import public return static switch typeof 
            default extends finally package private continue debugger 
            function arguments interface protected implements instanceof`
       .split(/\s+/)
       .reduce( (all, kw) => (all[kw]=true) && all, {} ),
    keyify = s => ( !(s in keywords) && /^[$A-Z_a-z][$\w]*$/.test(s) ? s : enquote(s) ) + ": ",
    enquote = s => s.replace(/([\\"])/g, '\\$1').replace(/\n/g,"\\n").replace(/\t/g,"\\t").replace(/^|$/g,'"'),
    traverse = obj =>  [ 
           `{`,
            indent( Object.keys(obj) 
                    .map( k => indent( keyify(k) + stringify[ typeof obj[k] ](obj[k]) ) )
                    .join(",\n")
                    ),
            `}`
        ]
        .filter( s => /\S/.test(s) )
        .join("\n")
        .replace(/^{\s*\}$/,"{}");
    return traverse(obj);
}

console.log(prettyPrint( 
    {
        "name":"Jon",
        "facts":{
            "car":"Ford",
            "address":{
               "city":"New York"
            },
            "watch":"Casio",
            "other": { 
                "true":false, 
                blargh:undefined, 
                "111number":1e5, 
                method:function(x){x++} 
            }
        }
    } 
));

2 of 2
1

A quick warning.

Javascript objects are referenced and that means objects can contain cyclic references. You function does not check for cyclic references. Cyclic references are very common in JavascripT so you should protect against the potential error.

Some solutions.

  • You can use a Set to track which objects have already been processed and step over repeats.
  • Add a depth argument that limits the recursion depth.

You can just let it throw a call stack overflow when the recursion gets too deep. However a warning, some browsers support tail call optimization and can recurse infinitely. Your function is not currently a tail call, but be aware as it could force the user to crash / close the page.

Example of cyclic object

 const A = {A: "Prop B be will reference Self" };
 A.B = A;