DEV Community

Cover image for How to Handle JSON Data in JavaScript (Asynchronous Guide)
WISDOMUDO
WISDOMUDO

Posted on

How to Handle JSON Data in JavaScript (Asynchronous Guide)

When building modern web applications, data often comes in the form of JSON, short for JavaScript Object Notation. JSON is an easy format used to share data between a web browser and a server. It’s lightweight, easy to read, and works perfectly with JavaScript.

But here’s the thing: fetching and handling JSON data doesn’t happen instantly.
That’s where asynchronous JavaScript steps in to help. It allows you to get data from a server without freezing your app or making users wait too long.

In this easy-to-follow guide, you’ll discover how to work with JSON data using JavaScript’s async tools like Fetch API and async/await.

What You’ll Learn

At the end of this guide, you’ll know:

  • What JSON is and why it’s important in web development
  • How to fetch JSON data using the Fetch API
  • How to handle JSON responses asynchronously
  • How to display and use JSON data in your application
  • Common mistakes to avoid when working with JSON

Understanding JSON in JavaScript

Before learning how to fetch and use JSON, it’s important to understand what JSON really is.

JSON (JavaScript Object Notation) is a data format that stores information in key-value pairs, much like JavaScript objects.

Let’s look at an example of what JSON data looks like:

{
  "name": "Wisdom",
  "age": 30,
  "city": "Port Harcourt"
}

Enter fullscreen mode Exit fullscreen mode

As you can see, JSON looks like a JavaScript object, but it’s written as text.
To use it in JavaScript, you must convert it into an object using JSON.parse().
And when sending data to a server, you convert it back to a string with JSON.stringify().

Now that you understand what JSON is, let’s see how to fetch it from a server.

Fetching JSON Data Asynchronously

In most real-world applications, data isn’t stored inside your code; it’s fetched from a server or an external API.

JavaScript provides the Fetch API to make this process easy and efficient.

Here’s a simple example:

fetch('https://jsonplaceholder.typicode.com/users')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error fetching data:', error));

Enter fullscreen mode Exit fullscreen mode

How it works:

  1. fetch() sends a request to the provided URL.
  2. response.json() converts the raw response into usable JSON data.
  3. The second .then() lets you use that data in your code.
  4. .catch() handles any possible network errors.

This is asynchronous because the code continues to run while it waits for the data, without freezing the app.

Next, let’s examine a cleaner approach to handling this using async/await.

Using Async/Await to Handle JSON

While .then() and .catch() work fine, using async/await makes your code cleaner and easier to read, especially for beginners.

Here’s how you can rewrite the same example:

async function getUsers() {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/users');
    if (!response.ok) throw new Error('Data could not be retrieved.');
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Error:', error.message);
  }
}

getUsers();

Enter fullscreen mode Exit fullscreen mode

What’s happening here:

  • You can utilize await inside the function by using the async keyword.
  • await pauses the code until the promise (data request) is complete.
  • response.json() converts the server response into readable JSON.
  • The try...catch block handles any errors that might occur.

Using async/await makes your code look more like regular step-by-step instructions, which is easier to follow.

Now that you know how to fetch JSON, let’s see how to work with and display it.

Working with JSON Data

Once you’ve fetched your JSON data, you can use it in different ways, like displaying it on a web page or storing it for later use.

Example:

async function showUserNames() {
  const response = await fetch('https://jsonplaceholder.typicode.com/users');
  const users = await response.json();

  users.forEach(user => {
    console.log(`Name: ${user.name}, Email: ${user.email}`);
  });
}

showUserNames();

Enter fullscreen mode Exit fullscreen mode

This example loops through the JSON data and logs each user’s name and email.

You could easily modify this to display the data in HTML elements using DOM manipulation.

Now that you can work with JSON data, let’s look at some common mistakes beginners make.

Common Mistakes to Avoid

When working with JSON asynchronously, beginners often make simple but avoidable errors. Here are a few to watch out for:

  • Forgetting to use .json(): Without it, you’ll get unreadable data.
  • Not checking response.ok: Always verify that your request succeeded before using the data.
  • Ignoring errors: Wrap your code in try...catch to handle failed requests.
  • Mixing async and then(): Choose one method for cleaner, more consistent code.

Avoiding these mistakes will make your code smoother and more reliable.

Conclusion

Handling JSON data in JavaScript is a key skill for anyone learning web development. It’s how your website communicates with servers and external APIs.
By learning to use the Fetch API and async/await, you can easily fetch, read, and use JSON data asynchronously without freezing your app.

Remember to handle errors properly, check your responses, and keep your code clean. The more you practice fetching and displaying JSON data, the more confident you’ll become in working with real-world APIs.

You can reach out to me via LinkedIn

Top comments (3)

Collapse
 
cristea_theodora_6200140b profile image
Theodora Cristea

Awesome post! Well explained!👏🏻

Collapse
 
wisdomudo profile image
WISDOMUDO

Thank you, I'm glad you find it useful. 👌

Some comments may only be visible to logged-in visitors. Sign in to view all comments.