The Wayback Machine - https://web.archive.org/web/20240813153520/https://www.geeksforgeeks.org/html-code-to-json-converter-app-using-html-css-and-javascript/
Open In App

HTML Code to JSON Converter App Using HTML, CSS, and JavaScript

Last Updated : 09 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

HTML tables are a common way to represent structured data on web pages, but transforming this data into a JSON format can be troublesome. JSON is a lightweight data-interchange format that is easy for humans to read and write and for machines to parse and generate.

We will be creating the HTML Code for the JSON Converter tool. The converter is designed to analyze HTML code, identify tables within it, and convert the table data into JSON format.

Prerequisites

Approach

  • Create an HTML structure that includes input fields for the user to enter the HTML code, a button to trigger the conversion, and an output field to display the JSON result.
  • Apply CSS styles to create an appealing layout for the app, making it visually engaging and user-friendly.
  • Create a function using JavaScript that converts data into JSON when the user clicks the “Convert to JSON” button.

Example: In this example, we will be demonstrating a JSON Converter app which converts the data into JSON format.

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width,
                   initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>HTML to JSON Converter</title>
</head>

<body>
    <div>
        <h1>HTML to JSON Converter</h1>
        <div class="container">
            <div class="input-container">
                <textarea id="htmlInput" placeholder="Paste your HTML code here">
              </textarea>
                <div>
                    <button onclick="convertToJson()">Convert to JSON</button>
                    <button onclick="clearFields()">Refresh</button>
                </div>
            </div>
            <textarea id="jsonOutput" readonly></textarea>
        </div>
    </div>
    <script src="script.js"></script>
</body>

</html>
CSS
body {
    font-family: Arial, sans-serif;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    margin: 0;
    background-color: #4caf50;
}

h1 {
    text-align: center;
    color: white;
}

.container {
    text-align: center;
    width: 1200px;
    justify-content: space-between;
    display: flex;
}

.input-container {
    margin-bottom: 20px;
}

textarea {
    width: 500px;
    height: 500px;
    padding: 10px;
    margin-top: 5px;
}

button {
    background-color: white;
    color: #4caf50;
    padding: 10px 20px;
    border: none;
    font-size: 18px;
    cursor: pointer;
    border-radius: 10px;
    border-color: #4caf50;
}

button:hover {
    font-weight: bold;
}
Javascript
const htmlInput = document.getElementById('htmlInput');
const jsonOutput = document.getElementById('jsonOutput');

// Function to convert table data into JSON
const convertToJson = () => {
    const htmlCode = htmlInput.value;
    const parser = new DOMParser();
    const doc = parser.parseFromString(htmlCode, 'text/html');
    const table = doc.querySelector('table');

    if (table) {
        const jsonData = extractTableData(table);
        if (jsonData) {
            const jsonString = JSON.stringify(jsonData, null, 2);
            jsonOutput.innerHTML = jsonString.replace(/, /g, ',<br>&nbsp;&nbsp;');
            // Formatting JSON for readability
        } else {
            jsonOutput.innerText = 'Table is missing some data.';
        }
    } else {
        jsonOutput.innerText = 'No table present in the given code.';
    }
};

// Function to extract table data and convert it to JSON format
const extractTableData = (table) => {
    const data = [];
    const headers = [];

    const headerCells = table.rows[0].querySelectorAll('th');
    for (const cell of headerCells) {
        headers.push(cell.innerText.trim());
    }

    for (let i = 1; i < table.rows.length; i++) {
        const tableRow = table.rows[i];
        const rowData = {};

        for (let j = 0; j < tableRow.cells.length; j++) {
            const cell = tableRow.cells[j];
            rowData[headers[j]] = cell.innerText.trim();
        }

        if (Object.values(rowData).some(value => value !== "")) {
            data.push(rowData);
        }
    }

    return headers.length === 0 || data.length === 0 ? null : data;
};

// Function to clear user input and output
const clearFields = () => {
    htmlInput.value = '';
    jsonOutput.innerHTML = '';
};

Output




Previous Article
Next Article

Similar Reads

How to parse JSON object using JSON.stringify() in JavaScript ?
In this article, we will see how to parse a JSON object using the JSON.stringify function. The JSON.stringify() function is used for parsing JSON objects or converting them to strings, in both JavaScript and jQuery. We only need to pass the object as an argument to JSON.stringify() function. Syntax: JSON.stringify(object, replacer, space); Paramete
2 min read
What is difference between JSON.parse() and JSON.stringify() Methods in JavaScript ?
JSON.parse() converts JSON strings to JavaScript objects, while JSON.stringify() converts JavaScript objects to JSON strings. JavaScript utilizes JSON for data interchange between servers and web pages. These methods enable easy data manipulation and transport in web development. JSON.parse() MethodJSON.parse() converts a JSON string to a JavaScrip
2 min read
Convert JSON String to Array of JSON Objects in JavaScript
Given a JSON string, the task is to convert it into an array of JSON objects in JavaScript. This array will contain the values derived from the JSON string using JavaScript. There are two approaches to solve this problem, which are discussed below: Approach 1: Using JSON.parse() MethodThe basic method to convert JSON String to Array of JSON object
2 min read
Create a Length Converter using HTML CSS and JavaScript
In this article, we will learn how to create a length converter using HTML, CSS, and JavaScript. The Length Converter is an intuitive web-based application that eliminates the complexities associated with manual conversions. Its user-friendly interface allows users to input a numerical value and select the units they want to convert from and to. Wi
6 min read
Temperature Converter using HTML CSS and JavaScript
In this article, we will see Temperature Conversion between Celsius, Fahrenheit &amp; Kelvin using HTML CSS &amp; JavaScript. The Temperature is generally measured in terms of unit degree., i.e. in degrees centigrade, in degrees, Fahrenheit &amp; Kelvin. Celsius is a standard unit of temperature on the Celsius scale, &amp; is represented by the °C
3 min read
Design a Unit Converter using HTML CSS and JavaScript
In this article, we will be developing an interactive and styled unit converter using HTML, CSS, and JavaScript.In this application, we have a select category option box in which different types of units are specified, like temperature, area, weight, length, and time. As per the user selection, the associated fields with the input fields are displa
7 min read
How to transforms JSON object to pretty-printed JSON using Angular Pipe ?
JSON stands for JavaScript Object Notation. It is a format for structuring data. This format is used by different web applications to communicate with each other. In this article, we will see How to use pipe to transform a JSON object to pretty-printed JSON using Angular Pipe. It meaning that it will take a JSON object string and return it pretty-p
3 min read
Build a Text to Speech Converter using HTML, CSS & Javascript
A text-to-speech converter is an application that is used to convert the text content entered by the user into speech with a click of a button. A text-to-speech converter should have a text area at the top so that, the user can enter a long text to be converted into speech followed by a button that converts the entered text into speech and plays th
3 min read
Javascript Program to Build a Morse Code Converter
In this article, we will create a Morse Code Translator app using HTML, CSS, and JavaScript. Morse code, a syste­m of encoding text characters into dot and dash se­quences. The app's functionality includes the ability to translate Morse­ code into text format. Output Preview: ApproachThe Morse­ Code Translator web application combines HTML, CSS, an
5 min read
JSON to XML Converter
JSON to XML Converter is a tool that converts the JSON file data to the XML file. #content-iframe {width: 100%; height: 720px;} @media (max-width: 768px) {.article--viewer .a-wrapper .content .text #content-iframe {max-width: 100%; min-height: 720px; height: auto;}} @media (max-width: 576px) {.article--viewer .a-wrapper .content .text #content-ifra
2 min read
three90RightbarBannerImg