StatusCake

The ultimate guide to working with JSON

json-coding

What is JSON?

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.

Data types

JSON can only store the following data types as values:

  • Number
  • String
  • Bool
  • Null
  • Object
  • Array

If you try to include functions, dates, or undefined in your JSON you are going to find yourself losing data.

Syntax

  • Data is in name/value pairs like JavaScript object properties
  • 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.

Avoid this:

Do this:

JSON Strings

String values in JSON are  wrapped in double-quotes:

JSON Numbers

A number value in JSON can be either an integer or a floating-point number, no quotes required:

JSON Booleans

Boolean values in JSON are true or false

JSON Nulls

Null values in JSON are defined by the keyword null

JSON Objects

Objects in JSON are wrapped in curly braces. We can list any number of key-value pairs, separated by commas inside the object:

JSON Arrays

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:

Using JSON in JavaScript

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.

JSON. Parse()

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!

JSON. Stringify()

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:

  • 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:

  • Objects 
  • Arrays 
  • Primitives:
  • strings,
  • numbers,
  • bools
  • Null.

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.

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

More from StatusCake

Buy vs Build in the Age of AI (Part 3)

5 min read Autonomous Code, Trust Boundaries, and Why Governance Now Matters More Than Ever In Part 1, we looked at how AI has reduced the cost of building monitoring tools. Then in Part 2, we explored the operational and economic burden of owning them. Now we need to talk about something deeper. Because the real shift isn’t

Buy vs Build in the Age of AI (Part 2)

6 min read The Real Cost of Owning Monitoring Isn’t Code — It’s Everything Else In Part 1, we explored how AI has dramatically reduced the cost of building monitoring tooling. That much is clear. You can scaffold uptime checks quickly, generate alert logic in minutes, and set-up dashboards faster than most teams used to schedule the kickoff

Buy vs Build in the Age of AI (Part 1)

5 min read AI Has Made Building Monitoring Easy. It Hasn’t Made Owning It Any Easier. A few months ago, I spoke to an engineering manager who proudly told me they had rebuilt their monitoring stack over a long weekend. They’d used AI to scaffold synthetic checks. They’d generated alert logic with dynamic thresholds. They’d then wired everything

Alerting Is a Socio-Technical System

3 min read In the previous posts, we’ve looked at how alert noise emerges from design decisions, why notification lists fail to create accountability, and why alerts only work when they’re designed around a clear outcome. Taken together, these ideas point to a broader conclusion. That alerting is not just a technical system, it’s a socio-technical one. Alerting

Designing Alerts for Action

3 min read In the first two posts of this series, we explored how alert noise emerges from design decisions, and why notification lists fail to create accountability when responsibility is unclear. There’s a deeper issue underneath both of those problems. Many alerting systems are designed without being clear about the outcome they’re meant to produce. When teams

A Notification List Is Not a Team

3 min read In the previous post, we looked at how alert noise is rarely accidental. It’s usually the result of sensible decisions layered over time, until responsibility becomes diffuse and response slows. One of the most persistent assumptions behind this pattern is simple. If enough people are notified, someone will take responsibility. After more than fourteen years

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

*By providing your email address, you agree to our privacy policy and to receive marketing communications from StatusCake.