DEV Community

Sahil Thakur
Sahil Thakur

Posted on

Working with JSON in Javascript

This post is originally written here with code samples and images -> https://easyontheweb.com/working-with-json-in-javascript/

I still remember my early days of learning web development, coming across the term JSON and getting scared for no reason at all. The term seemed daunting to me, mostly because I had no idea what it was. As it turns out, JSON is no mountain and in fact is your friend on the web. Therefore, in this article we’ll explore working with JSON in Javascript (the language of the web, ain’t it ?)

What exactly is JSON ?
Let us take a leaf directly out of JSON’s official documentation and just discuss a bit what JSON is and why should we be bothered about it ? Well, let’s answer the second question first.

JSON is important because we as web developers have decided to use it as the format in which we exchange data between servers and browsers and if you think about it, that is basically the entire web in a single line. So yeah, JSON is pretty important considering that it is the main format of information exchange on the web.

The JSON format is super lightweight which makes it an easy choice for the exchange of info., is actually just text but formatted in a very particular way such that it resembles objects when it comes to Javascript (or hashtables or whatever different names we’ve got for a DS that stores key-value pairs). Nearly every language has support for such a data structure and therefore can easily parse JSON.

Example of JSON
As you can very clearly see, the keys in JSON are strings (we’ll learn how to work with them in Javascript in the next section).

JSON and Javascript
JSON – Javascript Object Notation.

JSON literally has the word Javascript in it. Even though JSON is language independent it is written as Javascript Object Notation.

JSON itself exists as a string and Javascript actually provides a global module called JSON to work with it which we will take a look at later in this article.

Two terms that might come in handy are serialization and de-serialization. Serialization is to convert our data to a string so that it can successfully be transmitted as JSON whereas de-serialization is to accept string JSON data and convert it into usable data for us as developers or browsers to work with that data.

We will take a look at the JSON global module in Javascript but let us first take a look at how we can serialize and de-serialize data using the same module in Javascript.

JSON.stringify and JSON.parse
The two main functions that Javascript provides us to work with JSON data using it’s aptly named JSON global module are JSON.stringify() and JSON.parse(). They are used to serialize and de-serialize JSON data in Javascript so let us see how do they work.

JSON.stringify()
As we discussed before, when information needs to travel between server and browser, it needs to do so as text (or string as we know it). Therefore, what if we want to send some object data from our server (say any written on Node) to the browser ? We cannot do that as direct javascript object form. We first need to stringify the data and then send it through to the browser.

The JSON.stringify() function can be called with one or two parameters. The first parameter is the value that has to be converted into a JSON string.

JSON.stringify() example
As you can see in the code example every value that is passed into the function is wrapped as a string, even arrays and objects ! Also, another thing to note is that values like NaN, undefined etc. are all converted to null when JSON.stringify() is run on them.

One very interesting thing is a toJSON property that objects can have. If any object has this property then JSON.stringify() will only stringify based on this property’s rules. Let us see an example :-

This is a very powerful technique that I have myself used many times , mostly to filter data that should be. or should not be sent when a particular object is stringified into a JSON string.

The same thing can also be achieved by passing a second argument to the JSON.stringify() function called the replacer. The replacer is also used to filter out properties from the value to be stringified (but please note that the toJSON method can be used to do a whole variety of things, filtering was just an example).

The replacer can be a function or an array. If we pass it as an array, then only the values inside that array will be stringified and all the other values will be ignored. Let us see an example of the same thing we did above but by using the replacer array.

Using an array replacer is supercool and easy to do when it comes to filtering properties from the object but if you want a bit more fine grain control like the toJSON function you can use the replacer as a function.

This works nearly similar to toJSON so I guess you can use any that you like and that suits your needs actually.

Next, let us see how we can work with JSON data when we receive it rather than send it.

JSON.parse()
A sibling to the JSON.stringify() function is the JSON.parse() function which does the exact opposite of its brother.

What JSON.parse() does is take in a JSON string and converts it into it’s equivalent Javascript object (or any value for that matter).

This function takes in two arguments – one being the JSON string that needs to be converted into JS and the other being an optional function in which you can do a transformation of the object while parsing it. Let use see a simple example first :-

Pretty simple, right ? The main objective is clear – we just want to take in the json string and convert it into a Javascript value so that we can easily work with it in our program. Nothing special about it.

Let us also see an example of the optional second argument that you can pass into the JSON.parse() function.

Example from MDN docs
This function is just similar to the transformer we use with JSON.stringify() .

Two very important things to keep in mind that often trip developers up are these :-

JSON.parse() throws an error if the JSON string has trailing errors.
JSON.parse() throws an error if the JSON string has single quotes instead of double as key wrappers.

All three of them throw syntax errors
Final words
Even though working with JSON is pretty easy and especially in Javascript you can basically do it with just two of these functions, I think underestimating or getting overwhelmed by JSON is a bad thing. It is a great format to exchange information and we as web devs should leverage and appreciate it’s benefits.

For more information on JSON please check the MDN docs => https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON

For more javascript tips, tricks and content please check out the Javascript section of the blog here -> https://easyontheweb.com/category/javascript/

And if you want to be a part of a facebook group with other great web developers and also me please join this facebook group -> https://www.facebook.com/groups/503230450489995

Top comments (0)