To pretty print JSON in JavaScript using JSON.stringify(), use the third parameter, space, to control indentation and formatting:

  • Number: Pass a number (1–10) to specify the number of spaces for indentation.
    Example: JSON.stringify(obj, null, 2) uses 2 spaces per indentation level.

  • String: Pass a string (e.g., "\t", "--") to use that as the indentation character(s).
    Example: JSON.stringify(obj, null, "\t") uses a tab for indentation.

Key Points:

  • replacer (second parameter): Optional. Can be null (default) to include all properties, or a function/array to filter or modify values.

  • space (third parameter): Controls readability. If omitted or null, output is minified (no extra spaces).

  • Maximum spaces: If a number > 10 is used, JavaScript caps it at 10.

Example:

const obj = { name: "Alice", age: 30, city: "Berlin" };
console.log(JSON.stringify(obj, null, 4));

Output:

{
    "name": "Alice",
    "age": 30,
    "city": "Berlin"
}

Use Cases:

  • Debugging: Easily inspect object structure in logs.

  • Configuration files: Improve human readability.

  • React/HTML: Wrap output in <pre> tags to preserve formatting.

Tip: Use JSON.stringify(obj, null, 2) for a clean, readable default format.

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
If it is a number, successive levels in the stringification will each be indented by this many space characters. If it is a string, successive levels will be indented by this string. Each level of indentation will never be longer than 10. Number values of space are clamped to 10, and string values are truncated to 10 characters. ... JSON.stringify({}); // '{}' JSON.stringify(true); // 'true' JSON.stringify("foo"); // '"foo"' JSON.stringify([1, "false", false]); // '[1,"false",false]' JSON.stringify([NaN, null, Infinity]); // '[null,null,null]' JSON.stringify({ x: 5 }); // '{"x":5}' JSON.string
Discussions

TIL that JSON.stringify() will indent JSON for you! I used it to make a little JSON formatter, since the available ones have too many bells and whistles. Great project for beginners!

This is a cool little example. For anyone who doesn't know how to do this, the third argument in JSON.stringify is an option for how you want the parsed json to be indented (generally an integer denoting spaces or a string denoting the spaces). By default, it is not indented. What I normally do is:

JSON.stringify(json, null, 2);

What u/robertgfthomas did is a tiny bit more complicated, where he allows you to set the indent level based on the top-most text area, with "\t" (the tab character) - as a default:

textOut = JSON.stringify(JSON.parse(textIn), null, (indentLevel || '\t'));

And yes, I know this is basic stuff, but hopefully this will help someone become one of today's Lucky Ten Thousand.

More on reddit.com
🌐 r/javascript
27
73
July 18, 2016
Json, c#, pretty printing?
Alternatively, if you are using Newtonsoft, you can call JsonConvert.SerializeObject(object, formatting) passing Formatting.Indented as the second param to pretty print https://www.newtonsoft.com/json/help/html/M_Newtonsoft_Json_JsonConvert_SerializeObject_1.htm https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Formatting.htm Edit to answer your other question. Using Newtonsoft, you don't have to create a class to parse the JSON file. You can use JObect.Parse(object), but you and your tests will be much happier if you create a class and use JsonConvert.DeserializeObject(json) https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Linq_JObject.htm https://www.newtonsoft.com/json/help/html/M_Newtonsoft_Json_JsonConvert_DeserializeObject__1.htm I haven't looked in a while, but there might be a tool such that does what xsd.exe did to XML files and schemas for JSON. More on reddit.com
🌐 r/dotnet
13
2
June 18, 2020
Dictionary/JSON Pretty Print
For posterity, the Actions app has a Pretty Print Dictionaries action for this. More on reddit.com
🌐 r/shortcuts
7
22
January 18, 2020
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-pretty-print-json-string-in-javascript
How to Pretty Print JSON String in JavaScript? - GeeksforGeeks
July 12, 2025 - To pretty print JSON, you can format JSON strings with proper indentation, making them easy to read and debug. In JavaScript, you can achieve this using JSON.stringify() with optional parameters to specify the indentation level.
🌐
ReqBin
reqbin.com › code › javascript › ounkkzpp › javascript-pretty-print-json-example
How do I pretty print JSON in JavaScript?
To pretty-print JSON in JavaScript, you can use the JSON.stringify(obj, replacer, space) method. The third parameter of the JSON.stringify() method specifies the number of spaces to use when outputting the JSON string. If you pass a non-zero number, JSON.stringify() will generate pretty JSON with the specified number of white spaces in the JSON...
🌐
JSON Formatter
jsonformatter.org
Best JSON Formatter and JSON Validator: Online JSON Formatter
It uses $.parseJSON and JSON.stringify to beautify JSON easy for a human to read and analyze.
🌐
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 - So, how do we use JSON.stringify()? It's actually quite simple. All you need is your JSON object and the stringify() method. And if you want to make it look even prettier, just add null and '\t' as the second and third parameters.
Find elsewhere
🌐
EDUCBA
educba.com › home › software development › software development tutorials › javascript tutorial › json stringify pretty
JSON Stringify Pretty
April 12, 2023 - JSON Stringify Pretty helps to prettify JSON data and print it. ‘Pretty’ prettifies JSON content and ‘Print’ prints the prettified JSON content. PrettyPrint is an application that helps in converting various formats to text files or ...
Address   Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
🌐
W3Schools
w3schools.com › js › js_json_stringify.asp
JSON.stringify()
You can convert any JavaScript datatype into a string with JSON.stringify().
🌐
W3Resource
w3resource.com › JSON › snippets › json-stringify-pretty.php
JSON.stringify for Pretty Print
November 7, 2025 - replacer (optional): A function or array used to modify or filter the values during stringification. space (optional): A number or string used to insert white space and indentation into the output. If space is a number, it specifies the number of spaces to use for indentation (up to 10). If space is a string, it uses the string for indentation. ... // Define a JavaScript object const person = { name: "Sara", age: 25, department: "IT" }; // Convert object to a JSON string with pretty print (2 spaces indentation) const jsonString = JSON.stringify(person, null, 2); // Output the pretty-printed JSON string console.log(jsonString);
🌐
JSONLint
jsonlint.com › json-stringify
JSON Stringify - Escape JSON for Embedding | JSONLint | JSONLint
Convert JSON to an escaped string for embedding in code, databases, or other JSON. Handles quotes, newlines, and special characters.
🌐
Codemzy
codemzy.com › blog › express-pretty-print-json
Pretty print JSON responses with Express - Codemzy's Blog
June 27, 2024 - Here are some ways you can pretty print your JSON responses to the browser with Express in Node.js - either globally or for a single route, using the `space` property of `JSON.stringify()`.
🌐
JSON Formatter
jsonformatter.curiousconcept.com
JSON Formatter & Validator
The JSON Formatter & Validator beautifies and debugs JSON data with advanced formatting and validation algorithms.
🌐
DigitalOcean
digitalocean.com › community › tutorials › python-pretty-print-json
How to Pretty Print JSON in Python | DigitalOcean
September 16, 2025 - Reconstruct your custom Python objects from a JSON string by using the object_hook parameter in json.loads() to intercept and transform the data. Improve the debugging experience by using the rich library to pretty-print JSON with syntax highlighting directly in your terminal.
🌐
The Code Barbarian
thecodebarbarian.com › pretty-json-stringify-output.html
Pretty `JSON.stringify()` Output in JavaScript
However, by default, JSON.stringify() outputs minified JSON, with no whitespace or colors.
🌐
JSON Formatter
jsonformatter.org › json-stringify-online
JSON Stringify Online using JSON.Stringify()
It's very simple and easy way to create JSON String value and share Stringify data.
🌐
NGCC in Angular Ivy
iq.js.org › questions › react › how-to-pretty-print-json-with-react
How to pretty print JSON with React?
October 28, 2022 - To pretty print JSON with React, you can use the JSON.stringify() method and pass JSON object as the first argument, null as the second argument, and the 2 as the third argument.
🌐
Reddit
reddit.com › r/javascript › til that json.stringify() will indent json for you! i used it to make a little json formatter, since the available ones have too many bells and whistles. great project for beginners!
r/javascript on Reddit: TIL that JSON.stringify() will indent JSON for you! I used it to make a little JSON formatter, since the available ones have too many bells and whistles. Great project for beginners!
July 18, 2016 - This is a cool little example. For anyone who doesn't know how to do this, the third argument in JSON.stringify is an option for how you want the parsed json to be indented (generally an integer denoting spaces or a string denoting the spaces). By default, it is not indented.
🌐
GitHub
github.com › lydell › json-stringify-pretty-compact
lydell/json-stringify-pretty-compact: The best of both ` ...
While the “pretty” mode of JSON.stringify puts every item of arrays and objects on its own line, this module puts the whole array or object on a single line, unless the line becomes too long (the default maximum is 80 characters).
Author   lydell
🌐
FreeFormatter
freeformatter.com › json-formatter.html
Free Online JSON Formatter - FreeFormatter.com
<script> // A valid json string var someObject = {}; someObject.someProperty = "someValue"; // jsonString now contains a JSON string representation of someObject var jsonString = JSON.stringify(someObject); // Will display the string '{"someProperty":"someValue"}' alert(jsonString); </script>