Read JSON DATA and LOAD using JavaScript Async Await

Web Development

In this JavaScript tutorial you will learn how to load JSON Data from a JSON file and load the JSON data in to HTML drop down list using JavaScript Async await callback functions.

Load JSON data

Table of content

  • Starter code
  • Create a DB folder and a JSON file within the DB with the following data
  • How to validate JSON format
  • Add new style-json.css to the project
  • Create a new javascript file to read JSON
  • Load JSON data using async await
  • Use .then() to load the json data
  • Previous Project : State City Country Zip Code Drop Down code

Starter code

To get started with this javascript project, please create a new Project folder where you can copy and paste the starter code. The code for this project is split into multiple section so please tace care to copy it in correctly into each file.

At the end of the project you will find to complete code.

index.html code

The html file contains code from a previous project witch you can find here, as a blog post with source code, or you can watch the video version .

Down before the body closing tag you need to replace the `<script src=”main.js”></script> ` with the newly created <script src=”loadJSON.js”></script> in order to load the new script file for this project.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />

    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="style.css" />

    <title>Document</title>
  </head>
  <body>
    <h1>Select Country State City Zip</h1>
    <form class="dropdown-group">
      <select id="Country" size="1">
        <option value="" selected="selected">-- Select Country --</option>
      </select>

      <select id="State" size="1">
        <option value="" selected="selected">-- Select State --</option>
      </select>

      <select id="City" size="1">
        <option value="" selected="selected">-- Select City --</option>
      </select>

      <select id="Zip" size="1">
        <option value="" selected="selected">-- Select Zip --</option>
      </select>
    </form>
    <script src="main.js"></script>
  </body>
</html>

Create a DB folder and a JSON file within the DB with the following data

Create a new folder with the name of DB (data base, this is completely optional) and in this folder or outside of the folder create a JSON file and name it “data.json”.

The path will be later on relevant in your async code

How to validate JSON format

Now that you have your “data.json” file created it is time to populate it with some data. We are going to take the data from our previous project and add it to your JSON file.

var countryStateInfo = {
  USA: {
    California: {
      "Los Angeles": ["90001", "90002", "90003", "90004"],
      "San Diego": ["92093", "92101"],
    },
    Texas: {
      Dallas: ["75201", "75202"],
      Austin: ["73301", "73344"],
    },
  },
  Germany: {
    Bavaria: {
      Munich: ["80331", "80333", "80335", "80336"],
      Nuremberg: ["90402", "90403", "90404", "90405"],
    },
    Hessen: {
      Frankfurt: ["60306", "60308", "60309", "60310"],
      Surat: ["55246", "55247", "55248", "55249"],
    },
  },
};

This will result in a erro. Sorry :), the problem is that this is not json code.

But don’t worry, here is the solution. You can validate any code if it is valid json code by following this link for the JSON validator.

Your final VALID JSON code should look something like this. The you can Load JSON with JavaScript

{
  "USA": {
    "California": {
      "Los Angeles": ["90001", "90002", "90003", "90004"],
      "San Diego": ["92093", "92101"]
    },
    "Texas": {
      "Dallas": ["75201", "75202"],
      "Austin": ["73301", "73344"]
    }
  },
  "Germany": {
    "Bavaria": {
      "Munich": ["80331", "80333", "80335", "80336"],
      "Nuremberg": ["90402", "90403", "90404", "90405"]
    },
    "Hessen": {
      "Frankfurt": ["60306", "60308", "60309", "60310"],
      "Surat": ["55246", "55247", "55248", "55249"]
    }
  }
}

Add new style-json.css to the project

I changed up the style of this project just a little bit.

Create a new style-json.css file and copy the code below

* {
  margin: 0;
  padding: 0;
  font-family: "Open Sans", sans-serif;
}
h1 {
  margin-top: 4rem;
  text-align: center;
  font-size: 3rem;
}
body {
  background-color: #0a1853;
  color: #f9f9f9;
}
.dropdown-group {
  width: 200px;
  display: flex;
  flex-direction: column;
  gap: 20px;
  margin: auto;
  margin-top: 15vh;
}

select {
  width: 100%;
  min-width: 15ch;
  max-width: 30ch;

  border-radius: 0.25em;
  padding: 0.25em 0.5em;
  font-size: 1.25rem;
  cursor: pointer;
  line-height: 1.1;
  background-color: #fff;

  box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.2);
  transition: 0.2s ease;
}
select:hover {
  transform: scale(1.15);
  transition: 0.2s ease;
}
select:focus {
  border: 2px solid rgb(2, 255, 10);
  box-shadow: 0px 0px 15px 4px rgba(0, 0, 0, 0.5);
  transition: 0.2s ease;
}
option {
  background-color: #f9f9f9;
  color: #0a1853;
  transition: 0.2s ease;
  border-radius: 0.25em;
}

Don’t forget to replace the link with <link rel=”stylesheet” href=”style-json.css” />

Create a JavaScript file to read JSON

Now you need to create a loadJSON.js file where you will write the loading functions for the json code.

Copy in the code from the previous video that takes care of the form.

window.onload = function () {
  const countrySelection = document.querySelector("#Country"),
    stateSelection = document.querySelector("#State"),
    citySelection = document.querySelector("#City"),
    zipSelection = document.querySelector("#Zip");

  stateSelection.disabled = true;
  citySelection.disabled = true;
  zipSelection.disabled = true;

  for (let country in countryStateInfo) {
    countrySelection.options[countrySelection.options.length] = new Option(
      country,
      country
    );
  }

  // todo: Country Change

  countrySelection.onchange = (e) => {
    stateSelection.disabled = false;
    //   todo: Clear all options from state selection
    stateSelection.length = 1;
    citySelection.length = 1;
    zipSelection.length = 1;

    for (let state in countryStateInfo[e.target.value]) {
      stateSelection.options[stateSelection.options.length] = new Option(
        state,
        state
      );
    }
  };

  // todo: State Change

  stateSelection.onchange = (e) => {
    citySelection.disabled = false;

    citySelection.length = 1;
    zipSelection.length = 1;

    for (let city in countryStateInfo[countrySelection.value][e.target.value]) {
      citySelection.options[citySelection.options.length] = new Option(
        city,
        city
      );
    }
  };

  // todo: City Change

  citySelection.onchange = (e) => {
    zipSelection.disabled = false;

    zipSelection.length = 1;

    let zips =
      countryStateInfo[countrySelection.value][stateSelection.value][
        e.target.value
      ];

    for (let i = 0; i < zips.length; i++) {
      zipSelection.options[zipSelection.options.length] = new Option(
        zips[i],
        zips[i]
      );
    }
  };
};

Load JSON data using async await

At the start of the window.onload = function () {} is where you will create your asynchronous code that will load the JSON file using the await and fetch function.

Remember to create the code as the start of the function.

window.onload = function () {

  async function getCountryStateInfo() {
    const response = await fetch("data2.json");
    const data = await response.json();
    console.log(data);
    return data;
  }
getCountryStateInfo();
...
}

Initiate the function and open up your console in the browser where you should see your data loading using the console.log.

After you checked that the code loads you can comment out the console log and return the data.

Use .then() to load the json data

After you successfully loaded your JSON data you can now add the .then() method to the getCountryStateInfo() function.

Remember that the then() method returns a Promise. It takes up to two arguments: callback functions for the success and failure cases of the Promise. This mean that you must pass in the data.

  getCountryStateInfo().then((data) => {
    const countryStateInfo = data;
...
}

I suggest that you re-assign the data to a new variable called const countryStateInfo = data; in order to avoid replacing it in your future code.

Now you can move the rest of the code in your callback function and you should see your data from the JSON file being outputted in the form.

Thank you for your time

Hope you enjoyed this short HTML CSS and JavaScript Project, if you did then plase share it with others.

Video Tutorial

Check out the video tutorial for this post for a more detailed and visual explanation .

Previous Project : State City Country Zip Code Drop Down code

Check out more post like this

You might be interested in relevant Post link:

Become a web developer by taking my Course.

Latest Udemy Courses 

Coupon codes for all courses are already applied in order for you to have the best price possible !

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.