Understanding JSON in JavaScript: From Basics to Practical Application

Arkadipta kundu - Sep 21 - - Dev Community

A couple of days back, I delved deep into JSON (JavaScript Object Notation), and it’s been a game-changer in how I handle data in my JavaScript projects. Whether you’re new to JSON or want a refresher, this post will break down the basics, walk through converting between JavaScript objects and JSON, and show you how I used it to build a cool mini-project!

Let’s get started! 🚀


What is JSON?

JSON stands for Java*Script **Object **Notation. It’s a lightweight data format that's easy to read, write, and parse. JSON is commonly used for **storing* and transporting data, especially in APIs.

Here’s what a typical JSON object looks like:

{
  "user": {
    "id": 1,
    "name": "John Doe",
    "email": "john.doe@example.com",
    "address": {
      "street": "123 Main St",
      "city": "Anytown",
      "zipcode": "12345",
      "geo": {
        "lat": "40.7128",
        "lng": "-74.0060"
      }
    },
    "phone": "123-456-7890",
    "website": "johndoe.com",
    "company": {
      "name": "Doe Enterprises",
      "catchPhrase": "Innovation and Excellence",
      "bs": "business solutions"
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

JSON looks just like a JavaScript object — which is why it’s so handy when working in JavaScript! It’s a common format used in APIs to exchange data between servers and web applications.

For more information on JSON, here’s a great resource: w3schools JSON Introduction


Converting Between JavaScript Objects and JSON

There are two common tasks you’ll do with JSON:

  1. Convert a JavaScript object into a JSON string.
  2. Convert a JSON string back into a JavaScript object.

1. JavaScript Object to JSON

When you want to send data (like in an API request), you’ll often need to stringify a JavaScript object into JSON:

const jsonData = JSON.stringify(data);
Enter fullscreen mode Exit fullscreen mode

This converts your JavaScript object (data) into a JSON string that can be transmitted over the web.

2. JSON to JavaScript Object

When you receive JSON data (like in an API response), you’ll want to parse the JSON string into a JavaScript object so you can work with it:

const myJSON = '{"name":"John", "age":30, "car":null}';
const myObj = JSON.parse(myJSON);
Enter fullscreen mode Exit fullscreen mode

Once the JSON is parsed, you can access the data just like you would with any other JavaScript object!


Accessing Data from a JSON Object

Once you’ve converted the JSON string into a JavaScript object, you can easily access the data using dot notation or bracket notation.

Let’s say we have the following JSON string:

const jsonString = `
{
  "user": {
    "id": 1,
    "name": "John Doe",
    "email": "john.doe@example.com",
    "address": {
      "street": "123 Main St",
      "city": "Anytown",
      "zipcode": "12345",
      "geo": {
        "lat": "40.7128",
        "lng": "-74.0060"
      }
    },
    "phone": "123-456-7890",
    "website": "johndoe.com",
    "company": {
      "name": "Doe Enterprises",
      "catchPhrase": "Innovation and Excellence",
      "bs": "business solutions"
    }
  }
}
`;

const data = JSON.parse(jsonString); // Parsing the JSON string into an object
Enter fullscreen mode Exit fullscreen mode

Using Dot Notation

You can access data in a straightforward manner using dot notation:

console.log(data.user.name);        // "John Doe"
console.log(data.user.address.city); // "Anytown"
console.log(data.user.company.name); // "Doe Enterprises"
Enter fullscreen mode Exit fullscreen mode

Using Bracket Notation

Bracket notation works just as well, especially when dealing with dynamic properties:

console.log(data['user']['email']);     // "john.doe@example.com"
console.log(data['user']['address']['zipcode']); // "12345"
console.log(data['user']['company']['catchPhrase']); // "Innovation and Excellence"
Enter fullscreen mode Exit fullscreen mode

Both notations allow you to access deeply nested values in the JSON object. Pretty neat, right?


Challenge: Building a Taco Recipe Site with JSON

To put my JSON knowledge to the test, I built a mini-project: a Taco Recipe Site! The idea was simple — based on the type of taco the user selects (fish or chicken), it fetches the recipe from a JSON file and displays it on the site using EJS templates.

Here’s a quick overview of the project:

Steps I Followed:

  1. Created a JSON file containing different taco recipes.
  2. Set up an Express.js server.
  3. Used EJS for templating and to dynamically render the taco recipes based on the user’s selection.
  4. Parsed the JSON file to retrieve the appropriate recipe.

Example JSON Data:

Here’s a snippet of the JSON data used for the recipes:

{
  "tacos": [
    {
      "type": "fish",
      "ingredients": ["fish", "lettuce", "salsa", "tortilla"],
      "steps": ["Grill the fish", "Prepare the salsa", "Wrap it all in a tortilla"]
    },
    {
      "type": "chicken",
      "ingredients": ["chicken", "cheese", "lettuce", "tortilla"],
      "steps": ["Grill the chicken", "Add cheese and lettuce", "Wrap in a tortilla"]
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode

I then used this JSON data in my server code to display the appropriate recipe based on the user’s selection.

Code Example:

app.get('/taco', (req, res) => {
  const tacoType = req.query.type; // Get taco type (fish or chicken) from the request
  const taco = data.tacos.find(t => t.type === tacoType); // Find the matching recipe
  res.render('recipe', { taco }); // Render the recipe using EJS
});
Enter fullscreen mode Exit fullscreen mode

You can check out the full project code here: Taco Recipe Project.


Resources That Helped Me Learn JSON

Here are a few great resources that helped me on my journey to mastering JSON:

  1. W3Schools JSON Introduction - A beginner-friendly introduction to JSON.
  2. MDN Web Docs - JSON - A detailed guide from Mozilla Developer Network.
  3. YouTube: JSON Basics - A great YouTube video that simplifies the JSON concept.

In a Nutshell 🥜

JSON is one of the most important formats for working with data in web development, and learning how to effectively work with it has made handling data much easier for me. Whether you’re building APIs, fetching data from external sources, or working with configuration files, JSON is a tool you’ll use frequently.

Key Takeaways:

  • JSON is a lightweight and easy-to-read format for data.
  • Converting between JavaScript objects and JSON strings is super simple with JSON.stringify() and JSON.parse().
  • Once parsed into an object, accessing JSON data is as easy as working with JavaScript objects using dot or bracket notation.

I hope this post helped clear up any questions you might have about JSON! Feel free to reach out if you have any questions or want to share your own JSON-related projects.

. . . . . . . .
Terabox Video Player