JSON files as data store for small websites
If you need to display content on a website with repetitive markup, it becomes cumbersome to write the html by hand. You can see that is how i do it on https://arivugg.com. This is ok, if there are only few items.
The problem becomes challenging if you have to display 100’s of cards on a page for example like we can see on this page https://ganigapremierleague.com/players. The easiest way to achieve this is to use a JSON store and use javascript to generate the html.
All the player data is stored in a JSON in the format as below.
[
{
...
},
{
"id": "#2025-1",
"name": "Ramdas D",
"picture": "/assets/players/1.jpg",
"parents": "s/o Subbha Patali & Padmavati",
"category": "Batsman, Right Hand, Right Hand Fast",
"team": "vaniyanblastersseethangoli",
"taluk": "Mangalore",
"place": "Mangalore"
},
{
...
}
]
Then it is imported on to the html page like
import data from '/data/players.json' with { type: 'json' };
Now we have the JSON array ready to be parsed by Javascript.
The Javascript code to render each player card looks something like this.
function renderPlayers(inData) {
const section = document.getElementById("players");
if(section) {
for(const player of inData) {
const card = document.createElement("div");
card.classList.add("card", "player");
const playerImg = document.createElement("img");
playerImg.src = player.picture;
playerImg.setAttribute("loading", "lazy");
card.appendChild(playerImg);
const info = document.createElement("div");
info.classList.add("card-content");
const nameWithId = document.createElement("div");
nameWithId.classList.add('nameWithId');
const playerName = document.createElement("h4");
playerName.textContent = player.name;
nameWithId.appendChild(playerName);
const playerId = document.createElement("i");
playerId.classList.add('id');
playerId.textContent = player.id;
nameWithId.appendChild(playerId);
info.appendChild(nameWithId);
const playerPlace = document.createElement("h6");
playerPlace.textContent = player.place;
info.appendChild(playerPlace);
const playerParents = document.createElement("h6");
playerParents.textContent = player.parents;
info.appendChild(playerParents);
const playerCategory = document.createElement("small");
playerCategory.textContent = player.category;
info.appendChild(playerCategory);
card.appendChild(info);
section.appendChild(card);
}
}
}
This function is called in the html after we import it like renderPlayers(data)
The styling is done in the linked CSS file, the classes added using the element.classList.add("class")
call are used to target the elements.
This approach leads to no repetitive code and brings down maintainence overhead. Ofcourse since this is a JSON file we cannot write to it, thus can only be used as a static data source.