How to format JSON string in JavaScript?

To format JSON string in JavaScript, use JSON.stringify() with spacing parameters. This method converts JavaScript objects to formatted JSON strings with proper indentation for better readability.

Syntax

JSON.stringify(value, replacer, space)

Parameters

  • value - The JavaScript object to convert
  • replacer - Function or array to filter properties (use null for all properties)
  • space - Number of spaces or string for indentation

Example

var details = {
  studentId: 101,
  studentFirstName: 'David',
  studentLastName: 'Miller',
  studentAge: 21,
  subjectDetails: {
    subjectId: 'JavaScript_101',
    subjectName: 'Introduction to JavaScript'
  }
};

console.log("Not Pretty JSON Format:");
console.log(JSON.stringify(details));

console.log("\nPretty JSON Format:");
console.log(JSON.stringify(details, null, 2));
Not Pretty JSON Format:
{"studentId":101,"studentFirstName":"David","studentLastName":"Miller","studentAge":21,"subjectDetails":{"subjectId":"JavaScript_101","subjectName":"Introduction to JavaScript"}}

Pretty JSON Format:
{
  "studentId": 101,
  "studentFirstName": "David",
  "studentLastName": "Miller",
  "studentAge": 21,
  "subjectDetails": {
    "subjectId": "JavaScript_101",
    "subjectName": "Introduction to JavaScript"
  }
}

Different Spacing Options

var data = { name: "John", age: 30, city: "New York" };

console.log("4 spaces indentation:");
console.log(JSON.stringify(data, null, 4));

console.log("\nTab indentation:");
console.log(JSON.stringify(data, null, "\t"));

console.log("\nCustom string indentation:");
console.log(JSON.stringify(data, null, "-->"));
4 spaces indentation:
{
    "name": "John",
    "age": 30,
    "city": "New York"
}

Tab indentation:
{
	"name": "John",
	"age": 30,
	"city": "New York"
}

Custom string indentation:
{
-->"name": "John",
-->"age": 30,
-->"city": "New York"
}

Key Points

  • The third parameter controls indentation - use numbers for spaces or strings for custom indentation
  • Maximum indentation is 10 spaces when using numbers
  • Use null for the replacer parameter to include all properties
  • Formatted JSON is ideal for debugging and configuration files

Conclusion

Use JSON.stringify(obj, null, spaces) to format JSON with proper indentation. The third parameter makes JSON human-readable for debugging and display purposes.

Updated on: 2026-03-15T23:18:59+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements