How to Fetch JSON from GitHub and Display it on Your Website

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:

1. Host JSON File on GitHub

First, create a GitHub repository and upload your JSON file.

2. Fetch and Display JSON on Your Website

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>

Explanation

Here's a brief explanation of the code:

Demo