How to Fetch JSON from GitHub Repo as Raw Database

· JavaScript & Web · By Zeeshan Ahmad

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.

  • Create a New Repository

    Go to GitHub, create a new repository, and make it public.

  • Upload JSON File

    In your repository, click "Add file" and select "Upload files". Choose your JSON file and commit the changes.

  • Get the Raw URL

    Navigate to the JSON file in your repository and click Raw to get the raw URL of the 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:

bash
<!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:

  • HTML Structure: The basic structure includes a heading and a <pre> element to display the JSON data.
  • JavaScript: The fetch API is used to retrieve the JSON file from the GitHub URL. The JSON data is then displayed inside the <pre> element.

Demo

Related articles

Home · All Tools · Blog