JSON Formatter Script Documentation

Overview

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.

Function: 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';
    }
}

        

Explanation:

Usage in HTML

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.