Want to know how much website downtime costs, and the impact it can have on your business?
Find out everything you need to know in our new uptime monitoring whitepaper 2021
JavaScript Object Notation or JSON is a file format that was originally derived from JavaScript. It is used for storing and exchanging data, most commonly when serving data to websites, but JSON but has become ubiquitous amongst most programming languages as it is totally language independent. These days it is common to find JSON being used for a variety of purposes where data needs to be stored or transferred.
The beauty of JSON is found in its lightweight, human-readable nature, requiring less formatting than that of an alternative such as XML.
See the following example of an array of a cake object in both formats,
JSON
XML
I feel like there is a lot of duplication involved with XML, and I like to save my fingers work where I can (see Visual Studio Code shortcuts!) as well as the requirement of having to parse XML documents with an XML parser whereas JSON can be parsed with a common JavaScript function make choosing JSON an easy decision for me.
In this blog, I am going to cover the rules of how you should format a JSON object and how to use it in your coding projects.
JSON can only store the following data types as values:
If you try to include functions, dates, or undefined in your JSON you are going to find yourself losing data.
A key-value pair consists of a key (sometimes called a name), followed by a colon (:), followed by value. Both the key and the value must be wrapped in double quotes, for example:
Multiple key-value pairs are separated by a comma:
Each object described in JSON data must contain unique keys and they must be string values positioned to the left of the colon. While it is possible to use whitespaces in your keys, it is highly recommended to use underscores instead when there is a need to break up your key names, this will avoid any issues when your program is trying to access your keys later. Values do not have this restriction.
Avoid this:
Do this:
String values in JSON are wrapped in double-quotes:
A number value in JSON can be either an integer or a floating-point number, no quotes required:
Boolean values in JSON are true or false
Null values in JSON are defined by the keyword null
Objects in JSON are wrapped in curly braces. We can list any number of key-value pairs, separated by commas inside the object:
Arrays in JSON are a collection of JSON Objects separated by commas and encapsulated by square brackets.
With JSON you can store objects and arrays as values assigned to keys. It is extremely helpful for storing different sets of data in one file:
We now understand the rules around how to create JSON data structures, but how do you use them in practice? Luckily for us, JavaScript provides several methods for transforming data to JSON and vice versa.
Since we just created a JSON object, let us look at how to convert that into a JavaScript object.
This method takes in a string (our JSON object) and returns a JavaScript object. So, let’s take the JSON object we created above. Please note I have added the backslashes at the end of each line in the person string variable to allow for a multi-line string in the editor for better readability, you do not typically need to add these to your JSON strings
When we pass the person string as an argument to JSON. Parse() we get a native JavaScript object, in this case, I am calling this object personObject.
We can now access the personObjects properties using dot notation like any other JavaScript object because that is exactly what it is!
JSON.Parse() can also take an optional function(key, value) as second argument. This function will be called for each key, value pair and can transform the value. The documentation names this second argument as “reviver”.
When would we use the reviver argument? Well, recall when I said that JSON cannot store data type values such as Dates, well that is true, however using the reviver function as a second argument we can transform any key, value pair where we know the value is a Date stored as a string, and return it as the correct Date() type.
So, if we take the previous example and change the “age” property to “dob” and store a date value:
Then amend the JSON.Parse() signature to include a reviver function that will match any key with the name “dob” and try to convert the value into a JavaScript Date object:
Easy as that!
So, what about converting a JavaScript object to a JSON string you ask? Easy!
This method does the opposite of JSON.Parse(). It takes a JavaScript object as an argument and converts it into a JSON string. Here is an example,
First, we create a new object
Next, we create a new variable called JSONBook and assign it the return value of JSON.Stringify(book).
Now we have a variable that represents our object in JSON. Technically it is called a JSON-encoded or serialized or stringified or marshalled object, but that is a bit of a mouthful if you ask me.
Logging it to the console we can see it all looks good.
Now you could also save it in a file or send it back to the server for some processing.
Be aware that encoding the JSON object in this manner has several differences from the object literal:
As I mentioned above JSON supports the following data types:
If the object you are trying to stringify contains either:
they will simply get ignored by the serialization process, for example, if we create an object that contains a function as a property and an undefined value:
When we try to stringify it we only get the name value back as it is a valid data type; the other two properties are just ignored.
Like JSON.Parse(), JSON.Stringify() has a couple of optional arguments, the first of which is called a replacer. Using replacer allows us to pass in an array of properties to the function, only these properties will be encoded.
So, to show an example, here I am creating an object with a few properties but when I am calling JSON.Stringify() I am passing in an array as the second argument defining what values I want to return. And in true JavaScript fashion, if we pass in a property that cannot be found such as ‘roomNumber,’ it is just ignored.
That is handy, but I am sure you can see that an array list of property names could get quite long in some cases which is not ideal. Luckily, we can use a function instead of an array as the replacer argument.
The replacer function gets every key/value pair including nested objects and array items. It is applied recursively. You can see the function I have passed in as my replacer iterates over all the object keys and returns their values, that is unless the key is named ‘room,’ in that case undefined is returned which is ignored by JSON.Stringify().
NOTE: The value of this inside replacer is the object that contains the current property.
JSON.Stringify() has a third optional argument called space, this is used to define the number of spaces to use for pretty formatting. In all my examples above stringified objects included no indents or additional spaces. That would be suitable if we are just transferring the data to another system that will consume it. However, if we are saving our output to be read by humans, we want to think about formatting.
In the screenshot below I have set the space value to 2, this tells JavaScript to show nested objects on multiple lines, with indentation of 2 spaces inside of an object, I think you can agree this is much more human-readable:
Strangely enough, the space argument can also be provided as a string, which will be used for padding instead of spaces,
Honestly, I have never found a use for this, but I am suddenly hungry to see if I can…
I hope you have found this blog post useful. If you are developing for the web, you are going to run into JSON eventually, it is used everywhere and with good reason as I hope I have displayed in this post. Happy coding!
Share this
3 min read For any web developer, DevTools provides an irreplaceable aid to debugging code in all common browsers. Both Safari and Firefox offer great solutions in terms of developer tools, however in this post I will be talking about the highlights of the most recent features in my personal favourite browser for coding, Chrome DevTools. For something
6 min read There has certainly been a trend recently of using animations to elevate user interfaces and improve user experiences, and the more subtle versions of these are known as micro animations. Micro animations are an understated way of adding a little bit of fun to everyday user interactions such as hovering over a link, or clicking
2 min read Read about the latest websites that have experienced downtime including Netflix, Twitter, Facebook and more inside!
2 min read Read about how Google suffered an outage due to the soaring temperatures in the UK in July and how they rectified it right here!
3 min read See the results of our website downtime survey to see some of the most shocking and surprising stats! You won’t be disappointed.
6 min read Find out everything you need to know about Dark Mode and what you can do, as a developer, to make it easier to use.
Find out everything you need to know in our new uptime monitoring whitepaper 2021