Laboratory Experiment - 7

7. Develop JavaScript program (with HTML/CSS) for:

a) Converting JSON text to JavaScript Object

b) Convert JSON results into a date

c) Converting From JSON To CSV and CSV to JSON

d) Create hash from string using crypto.createHash() method

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>JSON and Crypto Operations</title>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js"></script>

    <style>

        body {

            font-family: Arial, sans-serif;

            margin: 20px;

        }

        .container {

            max-width: 800px;

            margin: auto;

        }

        textarea {

           width: 100%;

           height: 100px;

            margin: 10px 0;

        }

        button {

           margin: 5px;

           padding: 10px;

           background-color: #007BFF;

           color: white;

           border: none;

           cursor: pointer;

        }

        button:hover{

           background-color: #0056b3;

        }

        pre {

           background: #f4f4f4;

           padding: 10px;

        }

    </style>

</head>

<body>

    <div class="container">

        <h1>JSON and Crypto Operations</h1>

       

        <h2>a)Convert JSON Text to JavaScript Object</h2>

        <textarea id="jsonInput" placeholder="Enter JSON text"></textarea>

        <button onclick="convertJSONtoObject()">Convert to Object</button>

        <pre id="objectOutput"></pre>

 

        <h2>b)Convert JSON Results into a Date</h2>

        <textarea id="dateInput" placeholder='Enter JSON with a date, e.g., {"date": "2024-11-19T00:00:00Z"}'></textarea>

        <button onclick="convertJSONToDate()">Convert to Date</button>

        <pre id="dateOutput"></pre>

 

        <h2>c) Convert From JSON to CSV and CSV to JSON</h2>

        <textarea id="jsonToCsvInput" placeholder='Enter JSON array, e.g., [{"name":"John","age":30},{"name":"Jane","age":25}]'></textarea>

        <button onclick="convertJSONToCSV()">Convert to CSV</button>

        <pre id="csvOutput"></pre>

 

        <textarea id="csvToJsonInput" placeholder="Enter CSV data"></textarea>

        <button onclick="convertCSVToJSON()">Convert to JSON</button>

        <pre id="jsonOutput"></pre>

 

        <h2>d) Create Hash from String</h2>

        <input type="text" id="hashInput" placeholder="Enter a string" style="width: 100%; padding: 10px; margin: 10px 0;">

        <button onclick="createHash()">Generate Hash</button>

        <pre id="hashOutput"></pre>

    </div>

 

    <script>

        // a) Convert JSON text to JavaScript Object

        function convertJSONtoObject() {

            const jsonInput = document.getElementById("jsonInput").value;

            try {

                const obj = JSON.parse(jsonInput);

               document.getElementById("objectOutput").textContent = JSON.stringify(obj, null, 2);

            } catch (e) {

               document.getElementById("objectOutput").textContent = "Invalid JSON!";

            }

        }

 

        // b) Convert JSON Results into a Date

        function convertJSONToDate() {

            const dateInput = document.getElementById("dateInput").value;

            try {

                const obj = JSON.parse(dateInput);

                const date = new Date(obj.date);

                if (isNaN(date)) throw new Error("Invalid date");

                document.getElementById("dateOutput").textContent = `Date: ${date.toUTCString()}`;

            } catch (e) {

                document.getElementById("dateOutput").textContent = "Invalid JSON or date format!";

            }

        }

 

        // c) Convert JSON to CSV

        function convertJSONToCSV() {

            const jsonInput = document.getElementById("jsonToCsvInput").value;

            try {

                const array = JSON.parse(jsonInput);

                const csv = array

                    .map((row, i) =>

                        i === 0

                            ? Object.keys(row).join(",") + "\n" + Object.values(row).join(",")

                            : Object.values(row).join(",")

                    )

                    .join("\n");

               document.getElementById("csvOutput").textContent = csv;

            } catch (e) {

                document.getElementById("csvOutput").textContent = "Invalid JSON Array!";

            }

        }

 

        // Convert CSV to JSON

        function convertCSVToJSON() {

            const csvInput = document.getElementById("csvToJsonInput").value;

            try {

                const [headers, ...rows] = csvInput.split("\n");

                const keys = headers.split(",");

                const json = rows.map(row => {

                    const values = row.split(",");

                    return keys.reduce((acc, key, i) => {

                        acc[key] = values[i];

                        return acc;

                    }, {});

                });

                document.getElementById("jsonOutput").textContent = JSON.stringify(json, null, 2);

           } catch (e) {

                document.getElementById("jsonOutput").textContent = "Invalid CSV Format!";

            }

        }

 

        // d) Create Hash from String

        function createHash() {

            const input = document.getElementById("hashInput").value;

            if (!input) {

                document.getElementById("hashOutput").textContent = "Please enter a string.";

                return;

           }

            const hash = CryptoJS.SHA256(input).toString();

            document.getElementById("hashOutput").textContent = `Hash: ${hash}`;

        }

    </script>

</body></html>

 Output:


Explanation:

HTML (Structure)

  • Purpose: The backbone of the application, defining the structure and elements users interact with.

Key Elements:

  1. <textarea>:

    • Collects user input for various operations.
    • Example: Inputs for JSON strings, CSV strings, or plain text.
  2. <button>:

    • Triggers the respective JavaScript functions when clicked.
  3. <pre>:

    • Displays the processed output (formatted for readability).

CSS (Styling)

  • Purpose: Enhances the visual presentation of the application.

Key Features:

  1. Styles text areas (textarea) and buttons:
    • Width, height, colors, and hover effects improve user experience.
  2. Provides a clean layout with consistent spacing:
    • Ensures the application looks organized and professional.
  3. Formats the output display area (<pre>):
    • Adds a light background and padding for better readability.

JavaScript (Functionality)

  • Purpose: Implements all logic for processing input and displaying results.

1. Convert JSON Text to JavaScript Object

Function: convertJSON()

  • Input: A JSON string (e.g., {"name": "John", "age": 30}).
  • Process:
    • Uses JSON.parse() to convert the input string into a JavaScript object.
  • Output: Displays the object or shows "Invalid JSON!" if parsing fails.

2. Convert JSON Date

Function: convertToDate()

  • Input: A JSON string containing a date (e.g., {"date": "2024-11-19T00:00:00Z"}).
  • Process:
    • Parses the JSON, extracts the date value, and converts it to a JavaScript Date object.
  • Output: Displays the formatted date (e.g., Tue Nov 19 2024).

3. Convert JSON to CSV

Function: convertJSONToCSV()

  • Input: A JSON array (e.g., [{"name": "John", "age": 30}, {"name": "Jane", "age": 25}]).
  • Process:
    • Extracts keys as headers and maps values row-by-row into CSV format.
  • Output: Displays a CSV string:
    name,age
    John,30 Jane,25


4. Convert CSV to JSON

Function: convertCSVToJSON()

  • Input: A CSV string (e.g., name,age\nJohn,30\nJane,25).
  • Process:
    • Splits the input into rows, maps headers to values, and creates a JSON array.
  • Output: Displays the JSON array:
    json
    [
    {"name": "John", "age": "30"}, {"name": "Jane", "age": "25"} ]

5. Create Hash from String

Function: createHash()

  • Input: A plain text string (e.g., Hello, World!).
  • Process:
    • Uses the CryptoJS.SHA256 function to generate a SHA-256 hash.
  • Output: Displays the hash (e.g., a591a6d40bf420404a...).

How It Works Together

  1. User Input:
    • Text areas accept JSON, CSV, or strings based on the operation.
  2. Processing:
    • JavaScript functions handle the logic for parsing, converting, or hashing.
  3. Output:
    • Results are displayed in a readable format using <pre>.

Viva-Voce Questions:

HTML Questions: 
1. What is the purpose of the `<textarea>` element in this program? 
2. How does the `<button>` element trigger the associated JavaScript functions? 
3. What is the role of the `<pre>` element in the program? 
4. Why is the `placeholder` attribute used in the `<textarea>` tags? 

CSS Questions: 
1. How do you apply hover effects on buttons in CSS? 
2. Why is `padding` used in the styling of the `<pre>` element? 
3. How does the program ensure consistent styling across all text areas? 
4. Explain the role of `background-color` and `border-radius` in UI design.

JavaScript Questions: 
General: 
1. What is the difference between `JSON.parse()` and `JSON.stringify()`? 
2. How do you handle errors when parsing invalid JSON strings? 
3. What is the role of the `try-catch` block in the program?

Date Conversion: 
4. How does the `Date` object process ISO date strings in JavaScript? 
5. Why is `new Date()` used instead of directly accessing the date string? JSON and CSV Conversion: 
6. What are the key steps involved in converting JSON to CSV? 
7. How does the program extract headers from the JSON array for CSV conversion? 
8. What are the challenges in converting CSV back to JSON? Cryptographic Hashing: 
9. What is the purpose of generating a hash for a string? 
10. Why is `CryptoJS.SHA256` used instead of `crypto.createHash` in this program? 
11. How is hashing different from encryption? 

Web Development Questions: 
1. Why is external JavaScript loaded via `<script>` tags? 
2. What is the advantage of using `CryptoJS` for hashing in a browser environment? 
3. Can this program run offline? Why or why not?

Advanced Questions: 
1. How would you optimize the program for large JSON or CSV inputs? 
2. Can this program handle nested JSON structures for CSV conversion? If not, how would you extend it? 
3. Explain the limitations of using browser-based hashing compared to server-side hashing.

-:END:-

Comments

Post a Comment

Popular posts from this blog

Why to study Web Technology ?