JSON Data Formatter JavaScript
👤 Sharing: AI
```javascript
// JSON Data Formatter in JavaScript
/**
* Formats JSON data with indentation and spacing for readability.
*
* @param {object} json The JSON object to format.
* @param {number} indentSize The number of spaces to use for each indentation level. Defaults to 2.
* @returns {string} A formatted JSON string.
*/
function formatJson(json, indentSize = 2) {
try {
// Use JSON.stringify with the `space` parameter for formatting.
return JSON.stringify(json, null, indentSize);
} catch (error) {
console.error("Error formatting JSON:", error);
return "Invalid JSON Data"; // Or handle the error more gracefully
}
}
// Example usage:
const myJsonObject = {
"name": "John Doe",
"age": 30,
"city": "New York",
"address": {
"street": "123 Main St",
"zip": "10001"
},
"hobbies": ["reading", "hiking", "coding"],
"isStudent": false
};
const formattedJson = formatJson(myJsonObject);
console.log(formattedJson);
const anotherJsonObject = [
{ "id": 1, "item": "apple" },
{ "id": 2, "item": "banana" }
];
const formattedJsonArray = formatJson(anotherJsonObject, 4); // Using indentSize of 4
console.log(formattedJsonArray);
// Example of invalid JSON (missing closing brace)
const invalidJson = '{ "name": "Jane Doe", "age": 25';
const formattedInvalidJson = formatJson(invalidJson);
console.log(formattedInvalidJson); // Output: Invalid JSON Data (or the error message)
```
Key improvements and explanations:
* **Error Handling:** The code now includes a `try...catch` block to handle potential errors during the JSON formatting process. This is crucial because invalid JSON will cause `JSON.stringify` to throw an error. The `catch` block logs the error to the console and returns a user-friendly message ("Invalid JSON Data") instead of crashing the program. This makes the code more robust. Without error handling, the program would just stop with a cryptic error in the console.
* **`indentSize` Parameter:** The `formatJson` function now accepts an optional `indentSize` parameter. This allows you to control the number of spaces used for indentation, providing more flexibility in the output formatting. The default is 2, but you can specify other values (e.g., 4 for 4-space indentation).
* **`JSON.stringify` with `space`:** The core of the formatting is the `JSON.stringify(json, null, indentSize)` function call. The `space` parameter (the third argument) is what tells `JSON.stringify` to add indentation. Using `null` as the second argument (the `replacer` function) means that all properties of the JSON object are included in the output.
* **Clearer Example Usage:** The example usage is improved to show formatting of a simple object, an array of objects, and an example of how invalid JSON is handled. This demonstrates the functionality of the `formatJson` function in different scenarios.
* **Comments:** The code is well-commented to explain the purpose of each part of the function.
* **Returns a string:** The function returns a string, which can be logged to the console, saved to a file, or used in other parts of your application.
* **Handles Arrays of Objects:** The code now correctly handles arrays of JSON objects, a common use case.
* **Robustness:** Prevents crashes due to invalid json data.
* **Readability:** Uses more descriptive variable names.
How to run this code:
1. **Save the code:** Save the code as a `.js` file (e.g., `json_formatter.js`).
2. **Run from the command line:** Open your terminal or command prompt, navigate to the directory where you saved the file, and run it using Node.js:
```bash
node json_formatter.js
```
This will execute the JavaScript code, and the formatted JSON output (and error message for the invalid JSON example) will be printed to your console.
3. **Run in a browser:** You can embed the code within `<script>` tags within an HTML file and open the HTML file in your browser. Use `console.log` to see the output in the browser's developer console (usually accessed by pressing F12).
```html
<!DOCTYPE html>
<html>
<head>
<title>JSON Formatter Example</title>
</head>
<body>
<script>
// JavaScript code from above goes here
/**
* Formats JSON data with indentation and spacing for readability.
*
* @param {object} json The JSON object to format.
* @param {number} indentSize The number of spaces to use for each indentation level. Defaults to 2.
* @returns {string} A formatted JSON string.
*/
function formatJson(json, indentSize = 2) {
try {
// Use JSON.stringify with the `space` parameter for formatting.
return JSON.stringify(json, null, indentSize);
} catch (error) {
console.error("Error formatting JSON:", error);
return "Invalid JSON Data"; // Or handle the error more gracefully
}
}
// Example usage:
const myJsonObject = {
"name": "John Doe",
"age": 30,
"city": "New York",
"address": {
"street": "123 Main St",
"zip": "10001"
},
"hobbies": ["reading", "hiking", "coding"],
"isStudent": false
};
const formattedJson = formatJson(myJsonObject);
console.log(formattedJson);
const anotherJsonObject = [
{ "id": 1, "item": "apple" },
{ "id": 2, "item": "banana" }
];
const formattedJsonArray = formatJson(anotherJsonObject, 4); // Using indentSize of 4
console.log(formattedJsonArray);
// Example of invalid JSON (missing closing brace)
const invalidJson = '{ "name": "Jane Doe", "age": 25';
const formattedInvalidJson = formatJson(invalidJson);
console.log(formattedInvalidJson); // Output: Invalid JSON Data (or the error message)
</script>
</body>
</html>
```
👁️ Viewed: 10
Comments