The JSON Formatter script is a JavaScript function designed to format JSON strings into a readable format with proper indentation. This tool is useful for developers and users who need to quickly view and format JSON data for better readability.
formatJson
function formatJson() {
const jsonInput = document.getElementById('jsonInput').value;
const outputElement = document.getElementById('formattedJson');
try {
// Parse JSON and format it
const jsonData = JSON.parse(jsonInput);
const formattedJson = JSON.stringify(jsonData, null, 2);
outputElement.textContent = formattedJson;
} catch (e) {
// Handle JSON parse errors
outputElement.textContent = 'Invalid JSON';
}
}
The jsonInput
variable retrieves the JSON string from the HTML element with the ID jsonInput
. This is typically a <textarea>
or <input>
where users can paste or type their JSON data.
The outputElement
variable refers to the HTML element with the ID formattedJson
, where the formatted JSON will be displayed.
The function attempts to parse the JSON string using JSON.parse
. If successful, it formats the JSON with indentation (2 spaces) using JSON.stringify
.
If the input is not valid JSON, the error is caught by the catch
block, and 'Invalid JSON'
is displayed.
The formatted JSON or error message is displayed in the outputElement
by setting its textContent
.
To use the formatJson
function in your HTML page, include the following HTML structure along with the JavaScript function:
JSON Formatter
JSON Formatter
This HTML structure includes a <textarea>
for inputting JSON data, a <button>
to trigger the formatting function, and a <pre>
element to display the formatted JSON.