DEV Community

Cover image for Getting Started with JSON: Streamlining Data Handling for Beginners
Amrasakpare Lawrence
Amrasakpare Lawrence

Posted on • Updated on

Getting Started with JSON: Streamlining Data Handling for Beginners

Introduction

Hey there, Dev! πŸ˜€ If you're reading this article, chances are you already know that JSON (JavaScript Object Notation) is the language of modern data exchange. JSON has gained tremendous popularity due to its simplicity, versatility, and widespread support across various programming languages and platforms. Whether you're a seasoned developer or just starting your journey, understanding JSON is essential for effective data manipulation and integration. In this article, we'll dive into the syntax, structure, and practical exercises of JSON, exploring how it simplifies data interchange and equipping you with the skills to handle JSON data effectively. Let’s dive right into it πŸ˜‰

What is JSON

JSON stands for JavaScript Object Notation. It is a lightweight data-interchange format and the cool thing about it is that it is easy to read and write for humans and machines. JSON is a popular data interchange format for web applications.

Syntax

JSON is composed of key-value pairs. Each pair consists of a key (in double quotes) followed by a colon :, and then the corresponding value. Let’s see an example for easier understanding.

{
  "name": "John Doe",
  "age": 30,
  "city": "New York"
}
Enter fullscreen mode Exit fullscreen mode

From the example above, we have a JSON object representing a person's information. The object contains three key-value pairs: name with the value John Doe, age with the value 30, and city with the value New York.

It is important to know how to save a JSON file which is using the .json. Using the example above you can save the JSON file as personal_info.json.

Now that we know what the syntax is, Let’s look at the data types in JSON.

Data Types in JSON

-. JSON Strings

A string in JSON is a sequence of characters that are enclosed in double-quotes. The characters can be letters, numbers, symbols, and spaces.

Here is an example of a JSON string πŸ‘‡πŸ½

"name": "John"
Enter fullscreen mode Exit fullscreen mode

- JSON Strings

A number in JSON is a real number. The numbers can be integers, floats, or decimals.

Here is an example of a JSON number πŸ‘‡πŸ½

"age": 25, 
"pi": 3.14159
Enter fullscreen mode Exit fullscreen mode

- JSON Booleans

A boolean in JSON is a value that can be either true or false.

Here is an example of a JSON boolean πŸ‘‡πŸ½

"isReading": true
Enter fullscreen mode Exit fullscreen mode

- JSON Objects

An object in JSON is a collection of properties. The properties are key-value pairs. The key is a string, and the value can be a string, number, object, or array.

Here is an example of a JSON object πŸ‘‡πŸ½

{
  "name": "John Doe",
  "age": 30,
  "address": {
    "street": "123 Main Street",
    "city": "Anytown",
    "state": "CA",
    "zip": "91234"
  }
}
Enter fullscreen mode Exit fullscreen mode

In this example, the object has three properties: name, age, and address. The name property has a string value, the age property has a number value and the address property is an object.

- JSON Arrays

An array in JSON is a collection of values. The values can be strings, numbers, objects, or arrays.

Here is an example of a JSON array πŸ‘‡πŸ½

"grades": [90, 85, 95]
Enter fullscreen mode Exit fullscreen mode

In this example, the array has three values: 90, 85, and 95.

**- JSON Null**
Enter fullscreen mode Exit fullscreen mode

The null value in JSON represents a value that is undefined or unknown.

Here is an example of a JSON null value πŸ‘‡πŸ½

"middleName": null
Enter fullscreen mode Exit fullscreen mode

I know you must be very familiar with these data types we just talked about, but knowing the data types in JSON is important because it allows you to correctly interpret and handle the data in your applications very easily.

JSON Vs JavaScript Objects

It is important to point out the difference between JSON and JavaScript objects so that you’ll not be as confused as me when I first learned about it πŸ˜…

JSON

I know you already know what JSON is by now. But let’s see it in comparison to JavaScript objects.

JSON is a data format that is often used for data interchange between systems. It is language-independent and can be understood by many programming languages.

In JSON, all keys must be enclosed in double-quotes.

JSON requires strict adherence to its syntax rules.

Let’s see an example for better understanding πŸ‘‡πŸ½

{
  "name": "John Doe",
  "age": 30,
  "address": {
    "street": "123 Main St",
    "city": "New York",
    "country": "USA"
  }
}
Enter fullscreen mode Exit fullscreen mode

In this JSON example, the data is represented as a string. Keys are enclosed in double quotes, and values can be strings, numbers, objects, or other JSON data types.

JavaScript Objects

JavaScript objects are native to the JavaScript programming language and are used for data manipulation within JavaScript programs.

JavaScript objects allow for unquoted keys.

JavaScript objects allow for more flexibility.

const person = {
  name: "John Doe",
  age: 30,
  address: {
    street: "123 Main St",
    city: "New York",
    country: "USA"
  }
};
Enter fullscreen mode Exit fullscreen mode

In this JavaScript object example, the data is represented using JavaScript syntax. Keys are not enclosed in quotes, but values can still be strings, numbers, objects, or any valid JavaScript data type.

You can see that they are kind of opposite to each.
_
πŸ’‘ It's important to note that while the JSON syntax and JavaScript object syntax are similar, JSON requires keys to be enclosed in double quotes, whereas JavaScript objects allow for unquoted keys. Additionally, JSON is a data interchange format and requires parsing and stringification when interacting with it in programming languages, whereas JavaScript objects can be directly used and manipulated within JavaScript code._

JSON Parsing and Serialization

JSON parsing and serialization are important concepts when working with JSON data. Let’s take a detailed look at each of them πŸ‘‡πŸ½

JSON Parsing

JSON parsing refers to the process of converting a JSON string (JSON) into a native data structure (JavaScript Object) that can be used in your programming language. This allows you to extract and access the individual values stored in the JSON data.

Don’t worry yourself if you are finding it hard to wrap your head around it. Let’s see an example for a better understanding πŸ‘‡πŸ½

{
  "name": "John Doe",
  "age": 30,
  "address": {
    "street": "123 Main St",
    "city": "New York",
    "country": "USA"
  }
}

Enter fullscreen mode Exit fullscreen mode

The example above is a JSON string representing a person's information. Now to parse this JSON string, you would use the appropriate function provided by your programming language's JSON library. But since we are working with JavaScript, Here's how it is going to look like πŸ‘‡πŸ½

const jsonString = '{"name":"John Doe","age":30,"address":{"street":"123 Main St","city":"New York","country":"USA"}}';
const person = JSON.parse(jsonString);

console.log(person.name); // Output: John Doe
console.log(person.age); // Output: 30
console.log(person.address.city); // Output: New York
Enter fullscreen mode Exit fullscreen mode

From the code above, JSON.parse() is used to parse the JSON string jsonString into a JavaScript object (person). After parsing, you can access the individual values using dot notation (person.name, person.age, etc.). Hope it makes total sense now πŸ˜ƒ

JSON Serialization

JSON serialization is basically the opposite of JSON parsing. It is the process of converting a native data structure (such as an object or an array) into a JSON string. And it is most useful when you need to send or store JSON data.

Continuing with the previous example, let's serialize the person object back into a JSON string πŸ‘‡πŸ½

const person = {
  name: "John Doe",
  age: 30,
  address: {
    street: "123 Main St",
    city: "New York",
    country: "USA"
  }
};

var jsonString = JSON.stringify(person);
console.log(jsonString);
Enter fullscreen mode Exit fullscreen mode

The JSON.stringify() function is used to serialize the person object into a JSON string. The resulting JSON string can be logged out or used for various purposes, such as sending it over the network or storing it in a file. Here is what the output will be like πŸ‘‡πŸ½

{"name":"John Doe","age":30,"address":{"street":"123 Main St","city":"New York","country":"USA"}}
Enter fullscreen mode Exit fullscreen mode

Pretty easy right? πŸ˜‰

πŸ’‘ By understanding JSON parsing and serialization, you can effectively work with JSON data in your applications. Parsing allows you to extract data from a JSON string and work with it programmatically, while serialization enables you to convert native data structures into JSON for transmission or storage.

πŸ‘¨πŸ½β€πŸ’» Hands-On Exercise

Let’s build a very easy exercise with what we’ve discussed so far. πŸ‘‡πŸ½

Exercise: Create a Personal Information JSON File.

Here are the things we need in other to achieve the task πŸ‘‡πŸ½

  1. Create a JSON file named personal_info.json to store your personal information.

  2. Populate the JSON file with your personal details. Include properties such as:

    • "name": Your full name as a string.
    • "age": Your age as a number.
    • "email": Your email address as a string.
    • "address": Your address as an object with properties like "street", "city", "state", "zip", and "country".

You can use this data in the personal_info.json file instead πŸ‘‡πŸ½

{
  "name": "John Doe",
  "age": 25,
  "email": "johndoe@example.com",
  "address": {
    "street": "123 Main St",
    "city": "New York",
    "state": "NY",
    "zip": "10001",
    "country": "USA"
  }
}
Enter fullscreen mode Exit fullscreen mode
  • 3. Write a JavaScript program to read and display your personal information from the personal_info.json file.
    • Use the Fetch API or an appropriate method in your programming language to read the contents of the JSON file.
    • Parse the JSON data and store it in a variable.
    • Access the individual properties of your personal information and display them on the console or in a user-friendly format.

I know you are like β€œWhat is Fetch API doing in the exercise?”. The answer to your question is that since we are storing the data in a separate file (personal_info.json), we need to fetch it so that we can have access to all the data in the file. But if you do not know what Fetch API is, you can go quickly go through this article before starting the exercise πŸ‘‡πŸ½.

Fetch API

Promises

Here is the solution to the Exercise to compare with your own solution πŸ‘‡πŸ½

// Fetch the contents of the JSON file
fetch('personal_info.json')
  .then(response => {
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    return response.json();
  })
  .then(data => {
    // Access the individual properties and display them
    console.log('Name:', data.name); // John Doe
    console.log('Age:', data.age); // 25
    console.log('Email:', data.email); // johndoe@example.com
    console.log('Address:', data.address); // {street: '123 Main St', city: 'New York', state: 'NY', zip: '10001', country: 'USA'}
  })
  .catch(error => {
    console.error('Error:', error);
  });
Enter fullscreen mode Exit fullscreen mode

Let’s break down the explanation πŸ‘‡πŸ½

  1. The code starts by using the fetch function to make an HTTP request to retrieve the contents of the JSON file named "personal_info.json".

  2. The fetch function returns a promise that resolves to the response object representing the server's response to the request.

  3. The first .then() method is called on the promise returned by fetch. It checks if the response was successful (response.ok checks if the response status is within the 200-299 range). If the response is not successful, an error is thrown with a descriptive message including the status code.

  4. If the response is successful, the second .then() method is called, which extracts the JSON data from the response using the .json() method. This method returns another promise that resolves to the parsed JSON data.

  5. The callback function in the second .then() method receives the parsed JSON data as the data parameter. In this example, the individual properties of the JSON object are accessed (data.name, data.age, data.email, data.address) and logged to the console for display.

  6. If any error occurs during the fetch request or JSON parsing, the .catch() method is called, and the error is logged to the console.
    _
    πŸ’‘ Just to push yourself more, you can extract the data inside the address object._

Conclusion

Congrats on getting to this part of the article πŸŽ‰ πŸŽ‰. There are some things that I could not cover in this article that are a little bit advanced. But this article will definitely show you the basics of how JSON works. Till next week guys. Have a wonderful weekend πŸ˜€

Top comments (5)

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
devlawrence profile image
Amrasakpare Lawrence

Thanks chantal. I'm really happy that you found the article helpful

Collapse
 
rickdelpo1 profile image
Rick Delpo

my pal JSON should be your friend too
dev.to/rickdelpo1/my-pal-json-shou...

Collapse
 
preciousomovoiye profile image
Precious Omovoiye

This is a really helpful write up, thank you

Collapse
 
devlawrence profile image
Amrasakpare Lawrence

thanks bro. I really appreciate