There are so many programming languages, and every language has its own features. But all of them have one thing in common: they process data. From a simple calculator to supercomputers, they all work on data.

It's the same with humans: there are so many countries, so many cultures, and so much knowledge within each community.

But to communicate with other communities, people need a common medium. Language is to humans what JSON is to programming, a common medium of data transmission.

What is JSON?

JSON stands for JavaScript Object Notation. So before understanding JSON let's understand objects in JavaScript.

Every programming language has some method of storing similar data together. In C, for example, they are called structures.

In JavaScript, objects are a collection of key-value pairs, where values can be any variable (number, string, boolean), another object, or even a function. Objects are very useful in object-oriented programming.

Object-oriented programming is a programming paradigm based on the concept of "objects", which can contain data, in the form of fields, and code, in the form of procedures.

Let's look at an example.

In JavaScript, objects are defined using curly braces, for example:

var obj = {};

Here, obj is an empty object. You can also create objects using constructors, for example:

function Student(name, roll_number, age) {
  this.name = name;
  this.roll_number = roll_number;
  this.age = age;
}

var student1 = new Student("Abhishek", "123", 18);

console.log(student1.name, student1.roll_number, student1.age);
JS objects using constructors

This would give the output Abhishek 123 18.

This is how you create objects in JavaScript. But these objects are still variables that are only specific to JavaScript.

If you want to export these objects, and for example send them to a server, you need a method to encode them. Let's see how it's done.

JSON Stringify

In order to transmit data from one device to another, and one language to another, we need a structured, uniform and well-defined convention.

Though JSON is based on JS objects, certain conditions need to be valid. Luckily, you don't have to be worried about those conditions – because in JavaScript, we have a method called JSON.stringify().

This method is used to convert a JS object into an encoded string which can be transmitted anywhere without losing any data.

It might seem magical that any object can be encoded into a string and sent anywhere. Let's understand it more in-depth through some examples.

This is the prototype of the stringify method:

JSON.stringify(value[, replacer[, space]])

The first parameter is value which is the object you want to stringify. The second and third parameters are optional, and can be used if you want to customize how it be will encoded (for example, the separator and indentation).

Let's try to stringify our above example.

function Student(name, roll_number, age) {
  this.name = name;
  this.roll_number = roll_number;
  this.age = age;
}

var student1 = new Student("Abhishek", "123", 18);

var str = JSON.stringify(student1);

console.log(str);

This will give the output {"name":"Abhishek","roll_number":"123","age":18}.

If we use the optional parameters, that is we replace JSON.stringify(student1) with JSON.stringify(student1, null, 2), we will get something like this:

{
  "name": "Abhishek",
  "roll_number": "123",
  "age": 18
}

You can use these to print JSON in a readable format. Now let's try one more example.

Here we will be using object methods. Object methods are functions within an object which can be called with that object, using the methods in our above example:

function Student(name, roll_number, age) {
  this.name = name;
  this.roll_number = roll_number;
  this.age = age;
  this.print = function() {
    console.log(this.name, this.roll_number, this.age);
  }
}

var student1 = new Student("Abhishek", "123", 18);

student1.print();

This will give the same output as first example, that is, Abhishek 123 18.

Object methods can be used to execute functions associated with an object and use the properties of the object. Let's try to stringify this object.

function Student(name, roll_number, age) {
  this.name = name;
  this.roll_number = roll_number;
  this.age = age;
  this.print = function() {
    console.log(this.name, this.roll_number, this.age);
  }
}

var student1 = new Student("Abhishek", "123", 18);

var str = JSON.stringify(student1);

console.log(str);

It will still give you the same output,{"name":"Abhishek","roll_number":"123","age":18}.

Thus, the object methods are ignored by the stringify function. If you want them to be transmitted too, you need to convert them to a string first.

For example, you could call student1.print = student1.print.toString() and then stringify. Then you would get something like this:

{"name":"Abhishek","roll_number":"123","age":18,"print":"function() {\n    console.log(this.name, this.roll_number, this.age);\n  }"}

Let's consider another object:

var obj = {};

obj.key1 = "value1";
obj.key2 = obj;

var str = JSON.stringify(obj);

console.log(obj);

This will throw an error saying Uncaught TypeError: Converting circular structure to JSON.

This happens because key2 is referencing back to obj. Such objects are known as circular objects, and they cannot be converted to a JSON string.

This is where the second parameter comes in handy. Although I won't demonstrate how it works here, you can find the solution on this MDN page.

This is how you encode JSON. Now let's see how to parse a JSON string.

JSON parse

Just how JavaScript has a function to stringify JSON, we also have a function to parse that stringified JSON. This is the function prototype:

JSON.parse(text[, reviver])

Here, the first parameter is the JSON string which needs to be parsed. The second parameter is optional, and can be a function to modify the parsed JSON before returning. Let's demonstrate this method using an example.

function Student(name, roll_number, age) {
  this.name = name;
  this.roll_number = roll_number;
  this.age = age;
}

var student1 = new Student("Abhishek", "123", 18);

var str = JSON.stringify(student1);

var parsedJSON = JSON.parse(str);

console.log(parsedJSON,name. parsedJSON.roll_number, parsedJSON.age);

And the output will be Abhishek 123 18, so the JSON string was successfully parsed.

You could use this to send data from client to server. The data to be sent can be JSON encoded at the client and the stringified JSON will be parsed at the server and processed. This makes it really easy.

JSON can also be used to transmit data across different programs written in different languages. All languages have libraries to stringify and parse JSON.

JSON vs. XML

XML or eXtensible Markup Language is a very popular way of storing and transmitting data, similar to JSON. It existed before JSON and is still widely used today.

For example, it's used in RSS feeds, which are still the most popular way of subscribing to some publication or author. There are also XML sitemaps which are a list of all pages on a website. And search engines use them to see if there are any new pages to be crawled.

XML uses markup format – similar to HTML but much stricter.

JSON and XML have various similarities and differences, as explained in the following points:

  • Both are human-readable
  • Both have a hierarchial structure
  • Both are widely supported across various programming languages
  • Both can be fetched from the server using HTTP requests
  • JSON is shorter than XML
  • JSON can use arrays
  • JSON can be parsed using standard JavaScript functions, whereas XML needs to be parsed using the XML DOM (which is slower)

The same data can be expressed in JSON and XML as follows:

JSON:

{"employees":[
  { "firstName":"Quincy", "lastName":"Larson" },
  { "firstName":"Abigail", "lastName":"Rennemeyer" },
  { "firstName":"Abhishek", "lastName":"Chaudhary" }
]}

XML:

<employees>
  <employee>
    <firstName>Quincy</firstName> <lastName>Larson</lastName>
  </employee>
  <employee>
    <firstName>Abigail</firstName> <lastName>Rennemeyer</lastName>
  </employee>
  <employee>
    <firstName>Abhishek</firstName> <lastName>Chaudhary</lastName>
  </employee>
</employees>

JSON is better than XML for many reasons, but that doesn't mean we should abandon XML. Still, JSON will become the preferred form of data transmission in the future.

JWT - The future of JSON

JSON Web Token (JWT) is an open standard that defines a compact and self-contained way for securely transmitting information between parties as a JSON object.

This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA or ECDSA.

These tokens can be used to sign JSON data and verify the identity of the sender. Since the data is signed, if any data is has been tampered with you'll know it right away.

Though we won't discuss the implementation in full here, we can understand how it works. A JSON Web Token consists of three parts, the header, the payload and the signature.

The header consists of the type of token and algorithm used, the payload consists of the data, and the signature is the value you get when you sign the header and payload together.

The final token is in the form of <header>.<payload>.<signature>.

These tokens are currently used in authorization and are faster and more compact than other authorization methods. These may be very useful in the future and their potential is very high.

Conclusion

In this article, we've seen the importance of JSON as a medium of data transfer between completely different systems, and why is it so convenient.

JSON is a universal medium and is not just specific to JavaScript. JSON is already used in NoSQL databases to store data in JSON format.

We also compared JSON and XML and saw why JSON is more efficient and faster than XML. In the future, we may develop even better ways of transmitting data.

The rate at which the internet is growing, efficient data transfer will be the highest priority. And JSON serves that function really well for now.

You can try new things with JSON and implement different data structures – it's open to innovation, and we should never stop experimenting.

Hope you liked my article. I have learned a lot by writing it, and your appreciation motivates me everyday, Do visit my internet home theabbie.github.io.