How to Use JSON File in HTML Code

how to use json file in html code

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"> </script>

<script>

$(function() {

var people = [];

$.getJSON('people.json', function(data) {
$.each(data.person, function(i, f) {
var tblRow = "<tr>" + "<td>" + f.firstName + "</td>" +
"<td>" + f.lastName + "</td>" + "<td>" + f.job + "</td>" + "<td>" + f.roll + "</td>" + "</tr>"
$(tblRow).appendTo("#userdata tbody");
});

});

});
</script>
</head>

<body>

<div class="wrapper">
<div class="profile">
<table id= "userdata" border="2">
<thead>
<th>First Name</th>
<th>Last Name</th>
<th>Email Address</th>
<th>City</th>
</thead>
<tbody>

</tbody>
</table>

</div>
</div>

</body>
</html>

My JSON file:

{
"person": [
{
"firstName": "Clark",
"lastName": "Kent",
"job": "Reporter",
"roll": 20
},
{
"firstName": "Bruce",
"lastName": "Wayne",
"job": "Playboy",
"roll": 30
},
{
"firstName": "Peter",
"lastName": "Parker",
"job": "Photographer",
"roll": 40
}
]
}

I succeeded in integrating a JSON file to HTML table after working a day on it!!!

Trying to load local JSON file to show data in a html page using JQuery

As the jQuery API says: "Load JSON-encoded data from the server using a GET HTTP request."

http://api.jquery.com/jQuery.getJSON/

So you cannot load a local file with that function. But as you browse the web then you will see that loading a file from filesystem is really difficult in javascript as the following thread says:

Local file access with javascript

Using JSON files in html

You have to add some id attribute in html, then select based on that id and loop the json data and insert like this

<!doctype html>

<html lang="en">
<head>
<meta charset="utf-8">
<title>reading json</title>
<style>

</style>

</head>
<body>

<div id="json_result"></div>
<script>
function loadJSON(callback) {

var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'config.json', true); // Replace 'my_data' with the path to your file
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
// Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
callback(xobj.responseText);
}
};
xobj.send(null);
}

function init() {

loadJSON(function(response) {
// Parse JSON string into object
var actual_JSON = JSON.parse(response);

for (var key in actual_JSON) {
var innerkey = actual_JSON[key];
for (var inner in innerkey) {
document.getElementById('json_result').innerHTML += 'Example: '+innerkey[inner]['example']+'<br>';
document.getElementById('json_result').innerHTML += 'Example2: '+innerkey[inner]['example2']+'<br>';
}
}
});
}
init();
</script>

</body>

How to read an external local JSON file in JavaScript?

You cannot make a AJAX call to a local resource as the request is made using HTTP.

A workaround is to run a local webserver, serve up the file and make the AJAX call to localhost.

In terms of helping you write code to read JSON, you should read the documentation for jQuery.getJSON():

http://api.jquery.com/jQuery.getJSON/

Write multiple values from json file into HTML table with Javascipt

You can break down the code into little bite-sized functions that build up the table row-by-row creating HTML strings along the way, and then adding them to the DOM.

const data = {"628e191673ae8f7750c62fce":{name:"John",surname:"Smith",age:"24"},"628e1fd0d27981c6250d886c":{name:"Fred",surname:"Bloggs",age:"32"},"628e20c805f38641bdc08d7d":{name:"Joe",surname:"Harris",age:"27"}};

// Returns a simple cell
function getCell(data) {
return `<td>${data}</td>`;
}

// Returns an string of cells HTML
// `map` returns an array so we need to `join`
// the elements together
function getRow(data) {
return data.map(getCell).join('');
}

// Returns a set of rows by `mapping`
// over the values of each object, and creating
// a new row for each object
function getRows(data) {
return data.map(obj => {
const values = Object.values(obj);
return `<tr>${getRow(values)}</tr>`;
}).join('');
}

// Get the object values from the data
const objs = Object.values(data);

// Get the keys from the first object of `objs`.
// This way we don't have to hard-code the headings
// in the HTML markup
const headers = Object.keys(objs[0]);

// Construct a table using the functions
const table = `
<table>
<tbody>
<tr class="headings">${getRow(headers)}</tr>
${getRows(objs)}
</tbody>
</table>
`

// Add everything to a container
document.body.insertAdjacentHTML('beforeend', table);
table { border-collapse: collapse; border: 1px solid #454545; width: 300px;}
.headings { background-color: #efefef; font-weight: 600; text-transform: capitalize; }
td { padding: 0.3em; border: 1px solid #efefef;}

Create a json file from a html form

It seems you are on the frontend. You can't write files like this because of security. This would result in every website with some JavaScript being potentially able to write files to your system and you really don't want that.
Additionally fs is a Node API that is not available in the browser.

One option would be to download the JSON file from the frontend which you could do using the following code:

/**
* Download a JSON file.
* @param {sting} filename filename
* @param {any} obj any serializeable object
*/
function downloadJson(filename, obj) {
// serialize to JSON and pretty print with indent of 4
const text = JSON.stringify(obj, null, 4);

// create anchor tag
var element = document.createElement("a");
element.setAttribute(
"href",
"data:application/json;charset=utf-8," + encodeURIComponent(text)
);
element.setAttribute("download", filename);
// don't display the tag
element.style.display = "none";
// add tag to document
document.body.appendChild(element);
// click it: this starts the download
element.click();
// remove the tag again
document.body.removeChild(element);
}

window.addEventListener("DOMContentLoaded", (event) => {
// Start file download.
downloadJson("helloWorld.json", { hello: "World" });
});

If you add that to your page the save dialog will appear on a user's system. Here the one I am getting on Ubuntu:

Save dialog on Ubuntu for helloWorld.json

And here the content of the downloaded file:
helloWorld.json content after download

Please read this thread on the pros and cons of using an approach like this.



Related Topics



Leave a reply



Submit