preloader
Loading...
New webinar: "The Remote Job Search: My Microverse Journey" with graduate Paul Rail
Watch Now

We have launched an English school for software developers. Practice speaking and lose your fear.

Topics

At some point in our lives or careers in the development field, we all wondered: how can computers communicate with each other so easily and quickly? That is unbelievable.

Sometimes, you fill your username in on an application, and tons of data are there in a matter of seconds or less. How can this be?

In this article, you will understand how all this is possible and how to do it with JSON in JavaScript. So, if you don't know JS, it's a good time to learn the basics!

What is JSON?

JSON is a text-only format that follows the JSON syntax rules to send different data types.

To help you understand it quickly, JSON stands for JavaScript Object Notation. Besides that, JSON is compatible with almost every language.

This is possible because JSON is a lightweight format to communicate data between computers. It is easy to understand for all kinds of developers, and you can write or read it with code written in any programming language.

how to work with json in javascript
Image from private libarary

JSON Object VS JS Object

Before moving on, there are two concepts that we need to have well-differentiated to understand the core concepts of JSON in JavaScript. In this case, it's the difference between a JSON object and a JS object.

  • A JS object is just an unordered collection of key/value pairs, where the value can be whatever native data type we have in JS.
  • A JSON object is a data interchange format that saves a text version of a javascript object, but we won't execute any logic on it before parsing the string.

JSON Syntax Rules

JSON objects are structured to become native JavaScript objects without modifying them, so we need to follow a set of rules to validate that the JSON and JavaScript objects are identical.

These rules are:

  • Data has to be in key/value pairs, separated by a colon.
  • Data pairs have to be separated by a comma.
  • In data pairs, the key needs to be a unique double-quoted string.
  • The value can be any primitive data type but never a function.
  • Objects are written inside curly brackets.
  • Arrays are written inside square brackets.
how to work with json in javascript
Image from private librabry

JSON Functions in JavaScript

In JavaScript, we have two methods with which to work with JSON, and they work in a very intuitive way so everyone can learn them quickly. 

Stringify

The first one is the stringify method. This method allows the user to transform a JavaScript literal object into a JSON object, returning a string according to the value we passed to the function.

While working with the stringify method, we need to have in mind a couple of things to avoid errors, because if our JS object has undefined values, it will replace them with null, and if we have some unsupported data types, it can also censor them. To avoid this problem, you can also use the replace option after the value in the function, but for now, we will not dive deep into those situations.

how to work with json in javascript
Image from private library

Parse

The parse method will do the opposite of stringify. We will give the JSON object to this function, and it will convert it to a JS literal object.

To work with this method, we will need to be aware of the JSON object we are reading because if we Stringified it with the replacer option, we will need to implement the reviver option, but, again, these cases are very uncommon.

how to work with json in javascript
Image from private library

How to Access JSON Data

Using JSON in JavaScript leads us to 3 main ways to read the object literal that we need to work with, we can use dot notation, square brackets or object destructuring.

Below, you can see examples of each and decide which is the best for your use case.

Square Brackets Property Accessor

To access an object value using square brackets, we will make an object [‘key’] and it will return the value for the key we wanted.

how to work with json in javascript
Image from private library

Dot Notation

We can use dot notation to access the value for a specific key. The correct way to use it will be “object.key” and it will return the desired value.

how to work with json in javascript
Image from private libary

Object Destructuring

Object destructuring can be a bit confusing at the beginning, but is just a way to assign values to variables or constants all at the once, like in the example listed below:

how to work with json in javascript
Image from private library

Now that you understand the methods to do it, you can see how to loop through the array of JSON objects.

Why JSON?

JSON is already a standard. It became popular because JS is the principal developer's tool for the front-end. Having one standardized way to communicate data from another language as a JS object is necessary and makes life easier. Let's take, for example, a backend that retrieves an API, which has to be formatted to get consumed in the front-end. If the backend languages don't have the same syntax to write objects as JS, that will become a headache, and the front-end structure should change from app to app. But with JSON, we know that we can access the data retrieved very quickly, just calling the JSON method parse. Then we can use it as a regular JS object.

JSON Files

JSON files are files with the .json extension and are great for storing data in JSON format to be opened by any programming language and only need to be parsed to make it a JS object. These files are very useful because the code becomes lighter but still human-readable and editable with any code editor.

We may not see this kind of file too often since most of the connections between computers are via an internet connection, so we don't need to save the data in files on hard drives. But, pages such as Google+ allow users to download data in .json files they can use later.

Working With .json Files 

.json files are text-based, meaning we can open them with any code editor, but even if it's human readable, reading thousands or millions of entries is not a good idea.  With that in mind, we have two ways to read the files with JavaScript, allowing us to load the JSON object directly from a local file.

How to Load a JSON File in Javascript?

To load JSON files, we need to choose between require and fetch, and decide which is better for our case. If the file is locally saved in our computer, we should use require, thinking about the JSON file as another component of our project. On the other hand, if we need to read a file that is somewhere on the internet, we should use fetch, handling it as any other link.

Using Require()

If you request the file, as you will usually require a module from another JS file, you will be allowed to use all its content as regular JSON objects, parse it, and start working with it.

how to work with json in javascript
Image from private library

Using Fetch()

You can also use fetch, similar to making an HTTPS call, but that will make the code asynchronous, which will be useless if you have the file stored locally. However, this comes in very handy if you are in a web-based environment where you can have some delay while requesting the data.

how to work with json in javascript
Image from private library

Conclusion

JSON in JavaScript is a tool that allows developers to connect with applications written in many different languages, breaking the barriers between programs, and allowing them to receive and send information in a very lightweight format.

If you want to learn more about JSON, JavaScript, and how to code your own web applications you can do it by joining Microverse!

We have launched an English school for software developers. Practice speaking and lose your fear.

Subscribe to our Newsletter

Get Our Insights in Your Inbox

Career advice, the latest coding trends and languages, and insights on how to land a remote job in tech, straight to your inbox.

Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
We use own and third party cookies to; provide essential functionality, analyze website usages, personalize content, improve website security, support third-party integrations and/or for marketing and advertising purposes.

By using our website, you consent to the use of these cookies as described above. You can get more information, or learn how to change the settings, in our Cookies Policy. However, please note that disabling certain cookies may impact the functionality and user experience of our website.

You can accept all cookies by clicking the "Accept" button or configure them or refuse their use by clicking HERE.