What is JSON?
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,
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.
- Data is separated by commas
- Curly braces hold objects
- Square brackets hold arrays
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.
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.
Nesting JSON Objects and Arrays
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:
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:
Easy as that!
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:
- Strings use double quotes. No single quotes or backticks in JSON. So ‘John’ becomes “John”.
- Object property names are double quoted also. That is obligatory. So, age:30 becomes “age”:30.
As I mentioned above JSON supports the following data types:
If the object you are trying to stringify contains either:
- Function properties.
- Symbolic keys and values.
- Undefined Properties.
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.
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.
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!
More from StatusCake
7 min read The term “Design Pattern” describes a well-known and battle-tested solution to a problem that developers tend to encounter again and again when developing software. Here’s our step-by-step guides to the most useful ones!
4 min read The CSS landscape at the moment is ever-changing. There are many new features that have been released recently, so I thought I’d have a look around and summarise those that caught my eye, concisely in this post.
4 min read Wondering why your website is loading so slowly? Is your bounce rate off the scale? Are you dropping in SEO rankings? We’ve got you. Follow our handy guide to help you make your page load speed quicker!
3 min read Have you heard about domains being hijacked before? Did you know that yours could easily be at risk? Read about these 5 examples of domains that have been hijacked and how so you can make sure yours doesn’t fall victim too!
3 min read Not using website monitoring? Find out what happens to your website when you don’t, and how it can have long-last effects on your brand reputation!
3 min read Black Friday 2021 is fast approaching so we thought we’d help you out with everything you need to know about the biggest online event of the year!