Understanding and Implementing JSON and fetch()
Tags: javascript, html, json, beginners
Published: 2024-01-11 09:49:37

Jumping into my first project after starting my coding journey was one of the most intimidating things I've had to work through. That being said, once I got started, I jumped in with both feet first, and got to work. Not knowing I was getting a bit ahead of myself, as most coding beginners do, I found myself in a bit of a pickle when it came to my choice of creating my own data for the project. This left me with much to do in the world of JSON and `fetch()`, and to my surprise, a lot to learn. Now on the other side of the project, I have a much better understanding as to the fundamentals when using your own JSON file and connecting it to a web app using the `fetch()` method.

## Creating Your Data in the JSON Format

For a little background, let me explain the idea behind the web app I was developing. The goal was to create a simple web app for a salon which, when filtered, gave multiple cards containing information on two categories for appointments: hair and nail appointments. I discovered down the road that what I needed to do to have my own personalized data, was to create a JSON file.
JSON (JavaScript Object Notation) is a format used to interchange data across programming languages. A JSON file can be written into two configurations:

- A collection of names with their corresponding value pairs, which gets realized as an object. Or,
- a list of values, which gets realized as an array.

For my web app idea that includes various cards with information, an object like structure would be the most fitting. Lets say, a mock up of the list of appointments and their details looks something like this:

- Woman's Haircut: $30
- Men's Haircut: $20
- Coloring: $50
- Manicure: $25
- Pedicure: $30

Using this mock up, with the idea that we want to include an id number and an image, our data reformatted into the JSON format should look like this:

```
{
    "appointments": [
        {
            "id": 1,
            "name": "Woman's Haircut",
            "image": "insert image address",
            "price": 30
        },
        {
            "id": 2,
            "name": "Men's Haircut",
            "image": "insert image address",
            "price": 20
        },
        {
            "id": 3,
            "name": "Coloring",
            "image": "insert image address",
            "price": 50
        },
        {
            "id": 4,
            "name": "Manicure",
            "image": "insert image address",
            "price": 25
        },
        {
            "id": 5,
            "name": "Pedicure",
            "image": "insert image address",
            "price": 30
        }
    ]
}
```

## Accessing the JSON File Using fetch()

Now that our JSON file is all written up and correctly formatted, how do we access the data inside of it?

When you first start to write your JavaScript, you must think about when you want this data to be available to the rest of the page and the user. Typically, you would want this right as the page loads. In order to make that happen, we must code in a `DOMContentLoaded` event listener in our JavaScript file:

```
document.addEventListener('DOMContentLoaded', () => {
// We'll add this code in soon!
});
```

This now has an event listener so when the page loads up, it will run whatever code we ask it to right away.

We have our timing set up, now what? Well now have to grab the data! This is made possible by using the `fetch()` method:

```
document.addEventListener('DOMContentLoaded', () => {
  fetch('path to your data source')
    // Still more to add!
});
```

By passing `fetch()` the path or URL to our data source, it retrieves the data and holds on to it. `fetch()` returns a `Promise` object when it is called. A `Promise` object is essentially an eventual guarantee to do whatever you want it to do, when you ask it do such thing. Remember, this `Promise` is NOT the data. 

We've made it this far, however, `fetch()` cannot do anything with the data on its own. To actually interact with the data returned by `fetch()`, we must tell it to continue and move through the code. We do this by chaining on the `.then()` method:

```
document.addEventListener('DOMContentLoaded', () => {
  fetch('path to your data source')
    .then(function (response) {
      return response.json()
    })
    //Almost there!
});
```

The `.then()` method takes a callback function where we can do any necessary processing. This typically consists of using the built in `json()` method to translate the data from JSON. (`text()` is also a commonly used method that translates it into simple text.)
Though this notation is completely correct and will work, it is better practice to clean it up into a simple arrow function!:

```
document.addEventListener('DOMContentLoaded', () => {
  fetch('path to your data source')
    .then(response => response.json())
    //Just a little more!
});
```

So, we've retrieved the data and translated it. Still, we cannot just jump straight into the rest of our code. We must grab this translation, pass it again into a function, and then we can implement some DOM manipulation:

```
document.addEventListener('DOMContentLoaded', () => {
  fetch('path to your data source')
    .then(response => response.json())
    .then(function(data){
      // Now we can use our data!
    });
});
```

This new section of code can once again be simplified into a clear arrow function:

```
document.addEventListener('DOMContentLoaded', () => {
  fetch('path to your data source')
    .then(response => response.json())
    .then(data => {
      // Insert DOM Manipulation here.
    });
});
```

We now have the mock up list formatted into a JSON file, pulled into our JavaScript file, translated into usable data, and ready to be used throughout our code!

This was definitely the most confusing part of my entire project. Some of the terms that are a part of this whole process, are the most complex idea to understand, and as a beginner!? I sure was lost to start, but coming out of the end, I'm a lot more sure of myself, and I hope you may be too!

Happy Coding!