Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Prettify JSON data in textarea input in JavaScript?
JSON data can become difficult to read when it's minified or poorly formatted. JavaScript provides built-in methods to prettify JSON data in textarea elements using JSON.parse() and JSON.stringify().
How It Works
The process involves three steps:
- Parse the JSON string using
JSON.parse()to validate and convert it to an object - Use
JSON.stringify()with spacing parameters to format the object - Replace the textarea content with the prettified JSON
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JSON Prettifier</title>
</head>
<body>
<h3>JSON Prettifier</h3>
<textarea id="jsonInput" cols="80" rows="15" placeholder="Enter JSON data here..."></textarea>
<br><br>
<button onclick="prettifyJSON()">Prettify JSON</button>
<button onclick="clearTextarea()">Clear</button>
<script>
function prettifyJSON() {
try {
var textarea = document.getElementById('jsonInput');
var rawJSON = textarea.value.trim();
if (!rawJSON) {
alert('Please enter JSON data first');
return;
}
// Parse the JSON to validate it
var parsedJSON = JSON.parse(rawJSON);
// Stringify with 4 spaces for indentation
var prettifiedJSON = JSON.stringify(parsedJSON, null, 4);
// Update textarea with formatted JSON
textarea.value = prettifiedJSON;
} catch (error) {
alert('Invalid JSON format: ' + error.message);
}
}
function clearTextarea() {
document.getElementById('jsonInput').value = '';
}
// Sample JSON data for testing
window.onload = function() {
var sampleJSON = '{"name":"John","age":30,"city":"New York","hobbies":["reading","swimming"],"address":{"street":"123 Main St","zipcode":"10001"}}';
document.getElementById('jsonInput').value = sampleJSON;
};
</script>
</body>
</html>
Key Parameters
The JSON.stringify() method accepts three parameters:
| Parameter | Description | Example Value |
|---|---|---|
value |
The JavaScript object to stringify | parsedJSON |
replacer |
Function or array to filter properties |
null (include all) |
space |
Number of spaces for indentation |
4 (4 spaces) |
Error Handling
Always wrap JSON operations in try-catch blocks to handle invalid JSON:
<script>
function safeJSONPrettify(jsonString) {
try {
var parsed = JSON.parse(jsonString);
return JSON.stringify(parsed, null, 4);
} catch (error) {
console.error('JSON parsing failed:', error.message);
return 'Error: Invalid JSON format';
}
}
// Test with valid JSON
var validJSON = '{"test": "value"}';
console.log(safeJSONPrettify(validJSON));
// Test with invalid JSON
var invalidJSON = '{test: value}'; // Missing quotes
console.log(safeJSONPrettify(invalidJSON));
</script>
{
"test": "value"
}
Error: Invalid JSON format
Different Indentation Options
You can customize the formatting by changing the space parameter:
<script>
var data = {"name": "Alice", "scores": [95, 87, 92]};
// 2 spaces
console.log("2 spaces:");
console.log(JSON.stringify(data, null, 2));
// Tab character
console.log("\nWith tabs:");
console.log(JSON.stringify(data, null, '\t'));
// Custom string
console.log("\nCustom indentation:");
console.log(JSON.stringify(data, null, '--'));
</script>
2 spaces:
{
"name": "Alice",
"scores": [
95,
87,
92
]
}
With tabs:
{
"name": "Alice",
"scores": [
95,
87,
92
]
}
Custom indentation:
{
--"name": "Alice",
--"scores": [
----95,
----87,
----92
--]
}
Conclusion
Use JSON.parse() and JSON.stringify() together to prettify JSON data. Always include error handling for invalid JSON, and customize indentation using the third parameter of JSON.stringify().
Advertisements
