JSON Formatting & Validation JavaScript
👤 Sharing: AI
```javascript
/**
* Validates and formats a JSON string.
*
* @param {string} jsonString The JSON string to validate and format.
* @returns {object} An object containing:
* - `isValid`: A boolean indicating whether the JSON string is valid.
* - `formattedJson`: The formatted JSON string (or null if invalid).
* - `error`: An error message (or null if valid).
*/
function validateAndFormatJson(jsonString) {
try {
const parsedJson = JSON.parse(jsonString);
const formattedJson = JSON.stringify(parsedJson, null, 2); // Use 2 spaces for indentation
return {
isValid: true,
formattedJson: formattedJson,
error: null,
};
} catch (error) {
return {
isValid: false,
formattedJson: null,
error: error.message,
};
}
}
// Example Usage:
const validJson = '{"name": "John Doe", "age": 30, "city": "New York"}';
const invalidJson = '{"name": "John Doe", "age": 30, city: "New York"}'; // Missing quotes around 'city'
const validResult = validateAndFormatJson(validJson);
console.log("Valid JSON Result:", validResult);
const invalidResult = validateAndFormatJson(invalidJson);
console.log("Invalid JSON Result:", invalidResult);
// Example usage in a browser:
// You could take user input from a textarea, validate, and display the formatted JSON
// (or the error message) in another textarea or div.
function handleJsonInput() {
const jsonInput = document.getElementById("jsonInput").value;
const resultElement = document.getElementById("jsonResult");
const validationResult = validateAndFormatJson(jsonInput);
if (validationResult.isValid) {
resultElement.textContent = validationResult.formattedJson;
} else {
resultElement.textContent = "Error: " + validationResult.error;
}
}
// Add this to your HTML (e.g., in index.html):
/*
<!DOCTYPE html>
<html>
<head>
<title>JSON Validator and Formatter</title>
</head>
<body>
<label for="jsonInput">Enter JSON:</label><br>
<textarea id="jsonInput" rows="10" cols="50"></textarea><br>
<button onclick="handleJsonInput()">Validate & Format</button><br>
<label for="jsonResult">Result:</label><br>
<pre id="jsonResult"></pre>
<script>
function validateAndFormatJson(jsonString) { //... the function from above... }
function handleJsonInput() { //... the handleJsonInput function from above... }
</script>
</body>
</html>
*/
```
👁️ Viewed: 5
Comments