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
<!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>
Explanation:
HTML (Structure)
- Purpose: The backbone of the application, defining the structure and elements users interact with.
Key Elements:
<textarea>
:- Collects user input for various operations.
- Example: Inputs for JSON strings, CSV strings, or plain text.
<button>
:- Triggers the respective JavaScript functions when clicked.
<pre>
:- Displays the processed output (formatted for readability).
CSS (Styling)
- Purpose: Enhances the visual presentation of the application.
Key Features:
- Styles text areas (
textarea
) and buttons:- Width, height, colors, and hover effects improve user experience.
- Provides a clean layout with consistent spacing:
- Ensures the application looks organized and professional.
- 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.
- Uses
- 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 JavaScriptDate
object.
- Parses the JSON, extracts the
- 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:
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:
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.
- Uses the
- Output: Displays the hash (e.g.,
a591a6d40bf420404a...
).
How It Works Together
- User Input:
- Text areas accept JSON, CSV, or strings based on the operation.
- Processing:
- JavaScript functions handle the logic for parsing, converting, or hashing.
- Output:
- Results are displayed in a readable format using
<pre>
.
I really appreciate your efforts. Keep sharing such informative stuff. Really amazing. Thank you.
ReplyDeletestd tests in dubai
Cool
ReplyDelete