You are on page 1of 3

Web Development Assignment 04 on XML

Name :- Abhinav
Roll No:- HU21CSEN0500083

Task 1: Read a JSON object and display its content in an HTML table
Code :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JSON to HTML Table</title>
<style>
table {
border-collapse: collapse;
width: 100%;
}
th, td {
border: 1px solid black;
padding: 8px;
text-align: left;
}
th {
background-color: #f2f2f2;
}
</style>
</head>
<body>
<table id="jsonTable">
<thead>
<tr>
<th>Key</th>
<th>Value</th>
</tr>
</thead>
<tbody>
</tbody>
</table>

<script>
// JSON Object
var jsonObject = {
"Name": "John",
"Age": 30,
"City": "New York"
};

// Function to display JSON object in HTML table


function displayJSONInTable(jsonObject) {
var tableBody =
document.getElementById('jsonTable').getElementsByTagName('tbody')[0];
for (var key in jsonObject) {
var row = tableBody.insertRow();
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = key;
cell2.innerHTML = jsonObject[key];
}
}

// Call the function to display JSON object in HTML table


displayJSONInTable(jsonObject);
</script>
</body>
</html>

Output :

Task 2: Read JSON Array and convert it into a string using the stringify
function
Code :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JSON Array to String</title>
</head>
<body>
<div id="jsonArrayDisplay"></div>

<script>
// JSON Array
var jsonArray = [
{ "name": "John", "age": 30 },
{ "name": "Alice", "age": 25 },
{ "name": "Bob", "age": 35 }
];

// Convert JSON Array to String using JSON.stringify function


var jsonString = JSON.stringify(jsonArray);

// Display the stringified JSON Array


document.getElementById('jsonArrayDisplay').innerText = jsonString;
</script>
</body>
</html>

Output :

You might also like