Introduction to JSON

Introduction to JSON

And how it relates to JavaScript

Hi there,

You probably have seen file formats that end with a .json and probably do not understand what type of file it is. So, let's find out what they are!

JSON stands for JavaScript Object Notation. It is a file format which is a standard across different programming languages.

JSON files are used for a vast number of purposes in different programming languages, libraries and projects.

They have a basic format, as thus:

"key" : value

Where the value can be any data type, a string, an array, an object etc.

In JavaScript, a very common use case is in package.json which is a list of information that pertains to a specific project and its related package-lock.json.

A sample package.json file looks like

{
  "name": "reskill-americans-demo",
  "version": "1.0.0",
  "description": "A demo for reskill americans node js training",
  "main": "app.js",
  "scripts": {
    "test": "test"
  },
  "author": "Idris Lawal",
  "license": "MIT",
  "dependencies": {
    "uuid": "^8.3.2"
  },
  "devDependencies": {
    "nodemon": "^2.0.7"
  }
}

From the example above, we see for instance, a key named "name" and it value as as string called "reskill-americans-demo". Another key, "version" and its value as string "1.0.0". Then we also see another key named "scripts", but its value is an object { "test": "test"}.

Hence, a JSON is basically an object.

JavaScript has some in-built methods to handle JSON, two important ones are JSON.stringify() and JSON.parse, both methods work in opposite ways.

Let's see how they work.

When you have a JSON object which you want to store, maybe in a database or something similar, you might not be able to store the entire JSON as an object that it is, then you use the JSON.stringify method to help you convert it into a string that can be stored.

An example:

let employeeJSON = [
   {"first_name": "Math", "last_name": "Brains"},
   {"first_name": "Idris", "last_name": "Iron Man"}
]

Above, we have a JSON called employeeJSON which we want to save in the database, to do that, we need to convert it to a string that can be easily saved and retrieved later.

//converting JSON to string
let stringOfEmployeeJSON = JSON.stringify(employeeJSON) 

//let's see what it now looks like afterwards
console.log(stringOfEmployeeJSON)

//
'[{"first_name": "Math", "last_name": "Brains"}, {"first_name": "Idris", "last_name": "Iron Man"}]'

Notice the string and has a open and closing quote ' as strings usually do.

To convert the string back to a JSON object we can use the second method. JSON.parse().

let employeeJSONRetrieved = JSON.parse(stringOfEmployeeJSON)

console.log(employeeJSONRetrieved)

//
[
   {"first_name": "Math", "last_name": "Brains"},
   {"first_name": "Idris", "last_name": "Iron Man"}
]

That's it!

I hope you now will able to understand JSON files and use them in your code. Cheers!