DEV Community

Cover image for Displaying Content On The Webpage Using A Local JSON File.....
Shashi
Shashi

Posted on • Updated on

Displaying Content On The Webpage Using A Local JSON File.....

Want to learn and experiment with how data gets exchanged between different files using JSON locally with a small practice project?

For the next few minutes, please forget about JaSON (Statham) from the "The Transporter" and "Fast & Furious"- and just read on, and then later code on. By the end, you will say you know little bit of another JSON, I promise. Okay, that's a bad joke.

I made this simple project to understand how this works with a local JSON file.

Some Fast & Furious Bytes about JSON.

  • JSON stands for Java Script Object Notation
  • JSON is a complete platform and language independent.
  • JSON is a text based format file, So it's easy to read and understand even for non-coders.
  • JSON mostly used for asynchronous transactions.
  • We can convert any Javascript Object into JSON and send it to the server. Server will then process it and send it back to the Javascript in JSON format.

Project Demo: Render JSON

Project Snapshot:
Render JSON

Here is the Project's Source Code:

index.html

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>JavaScript JSON List</title>
  <link rel="stylesheet" href="style.css">
</head>

<body>
  <div>
    <h1>[ Displaying Content On The Webpage From Local JSON File ]</h1>
  </div>
  <hr />
  <div class="output"></div>
  <script src="app.js"></script>
</body>

</html>
Enter fullscreen mode Exit fullscreen mode

style.css

body {
  font-family: 'Roboto', sans-serif;
  background-color: #070116;
}

div {
  text-align: center;
  background-color: rgb(41, 216, 216);
  padding: 10px;
}

.output {
  text-align: center; 
  color: white; 
  font-size: 20px;
}

.active {
  margin: 40px;
  padding: 50px;
  font-size: 20px;
  color: white;
  letter-spacing: 2px;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  background-image: linear-gradient( 160deg, #ff0000, #ec008c );
  border-radius: 30px;
  cursor: pointer;
}
Enter fullscreen mode Exit fullscreen mode

local.json

[
  {
    "firstName": "Shash",
    "lastName": "WebDev",
    "gender": "male",
    "age": 35,
    "address": {
      "streetAddress": "123",
      "city": "Greater Manchester",
      "postalCode": "M32"
    },
    "phoneNumbers": [{ "type": "home", "number": "123456789" }]
  },
  {
    "firstName": "Rihan",
    "lastName": "Anne",
    "gender": "Female",
    "age": 28,
    "address": {
      "streetAddress": "019",
      "city": "Dublin",
      "postalCode": "D01"
    },
    "phoneNumbers": [{ "type": "home", "number": "238047651" }]
  },
  {
    "firstName": "John",
    "lastName": "Smith",
    "gender": "male",
    "age": 38,
    "address": {
      "streetAddress": "456",
      "city": "London",
      "postalCode": "E1"
    },
    "phoneNumbers": [{ "type": "home", "number": "987654321" }]
  },
  {
    "firstName": "Kelly",
    "lastName": "Brokes",
    "gender": "Female",
    "age": 32,
    "address": {
      "streetAddress": "789",
      "city": "Glasgow",
      "postalCode": "G1"
    },
    "phoneNumbers": [{ "type": "home", "number": "345672198" }]
  }
]
Enter fullscreen mode Exit fullscreen mode

app.js

"use strict";

const output = document.querySelector(".output");
//console.log(output); // <div class="output"></div>

//output.textContent = "New Content";
//console.log(output); // <div class="output">New content</div>

// Storing json data in a variable
const localJsonFile = "local.json";

// The DOMContentLoaded event fires when the initial HTML document has been completely loaded and parsed,
// without waiting for stylesheets, images, and subframes to finish loading.
window.addEventListener("DOMContentLoaded", () => {
  // console.log('DOM fully loaded and parsed');
  output.textContent = "Loading....";
  // Make fetch request to local.json file
  fetch(localJsonFile)
    .then((response) => response.json()) // and the response we get is in json format
    .then((data) => {
      // we call that data here
      // console.log(data); // check the data on the console
      output.innerHTML = ""; // Initial content is empty
      data.forEach((el) => {
        // loop through the json data using forEach method
        // console.log(el);
        jsonList(el); // calling jsonList function
      });
    });
});

// Create a function to display the json data dynamically on the webpage
function jsonList(item) {
  // Create a new div element dynamically
  const div = document.createElement("div");
  // get the required details from the local.json file to the div element using innerHTML
  div.innerHTML = `
        ${item.firstName} ${item.lastName} is a ${item.gender} of ${item.age},
        resides in ${item.address["streetAddress"]} ${item.address["city"]} ${item.address["postalCode"]}
        with a contact number ${item.phoneNumbers[0]["number"]}.`;
  // attach the newly created div element to the original div element, in this case to the class '.output'
  output.append(div);
  // Add styling to the displayed content
  div.classList.add("active");
}

Enter fullscreen mode Exit fullscreen mode

If you want to experiment, just add some content to local.json file and see how it updates the webpage dynamically.

Happy C❤️ding!!

Top comments (0)