Cookie Consent by Free Privacy Policy Generator

Output JSON Data into Readable HTML

The JavaScript tutorial shows an easy method to extract the contents of a JSON file and output in an HTML webpage. Modify and expand on the script to meet your requirements.


Step 1​


Copy and paste the JS script below into the intended webpage. Update the data.json file location if different.

Code:
<script>
// fetch the data.json file from with same folder - not remote
        fetch('data.json')
            .then(function (response) {
                return response.json();
            })
            .then(function (data) {
                appendData(data);
            })
            .catch(function (err) {
                console.log('error: ' + err);
            });

// create a function to extract the JSON data and create a HTML element to output
        function appendData(data) {
            var mainContainer = document.getElementById("jsonData");
            for (var i = 0; i < data.length; i++) {

// create and output the data
                var div = document.createElement("div");
                div.innerHTML = 'Town: ' + data[i].town + ' ' + data[i].county;
                mainContainer.appendChild(div);
            }
        }
    </script>

Step 2​


Manually insert the div id shown below into the webpage HTML where you want to render the JSON file contents.

Code:
<div id="jsonData"></div>

Contents of the data.json file​

Code:
[
    {
        "id": "1",
        "town": "Wigan",
        "county": "Greater Manchester"
    },
    {
        "id": "2",
       "town": "Oldham",
       "county": "Greater Manchester"
    },
    {
   "id": "3",
       "town": "Stockport",
       "county": "Greater Manchester"
    }
]
 
Back
Top