In this blog post, we'll walk through the steps to host a JSON file on GitHub and then fetch and display it on your website using JavaScript. Below are the detailed steps:
First, create a GitHub repository and upload your JSON file.
Go to GitHub, create a new repository, and make it public.
In your repository, click "Add file" and select "Upload files". Choose your JSON file and commit the changes.
Navigate to the JSON file in your repository and click Raw to get the raw URL of the file.
Use the following HTML and JavaScript to fetch the JSON file from GitHub and display it on your website:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Fetch JSON from GitHub</title>
</head>
<body>
<h1>Data from JSON</h1>
<pre id="json-data"></pre>
<script>
// Replace with your raw JSON URL from GitHub
const jsonUrl = 'https://raw.githubusercontent.com/yourusername/yourrepository/branch/yourfile.json';
fetch(jsonUrl)
.then(response => response.json())
.then(data => {
document.getElementById('json-data').textContent = JSON.stringify(data, null, 2);
})
.catch(error => console.error('Error fetching JSON:', error));
</script>
</body>
</html>
Here's a brief explanation of the code:
<pre>
element to display the JSON data.
fetch
API is used to retrieve the JSON file from the GitHub URL. The JSON data is then
displayed inside the <pre>
element.