What is JSON?
Ekaterine Mitagvaria
Posted on November 10, 2023
JSON stands for JavaScript Object Notation and it's a file format that is used to exchange or share various data across different systems or applications (e.g. from server to client). Transmission of data can be done using various file formats like XML or CSV however today we are going to cover JSON.
JSON is very human-readable and easy to understand which makes it one of the most popular file formats. It is structured data based on JavaScript syntax which makes it easier to convert JSON to JavaScript objects. You can also use JSON in other programming languages like Python or Java.
JSON syntax
JSON syntax is very similar to JavaScript object syntax but it's not the same. There are a couple of things you need to remember about JSON syntax:
- It consists of key/value pairs separated by colons
- The keys need to be strings and values can be strings, numbers, objects, booleans, arrays, and null.
- The key/value pairs are separated by a comma
- The JSON needs to be wrapped by curly braces ( {} )
JSON Strings Example
JSON Numbers Example
JSON Booleans Example
JSON Objects Example
JSON Arrays Example
JSON Null Example
Let's create one JSON ourselves that has various data types:
In the example above, we create a person named Anna, with age 30, whose boolean value of isStudent is set to false, with an address object that consists of key/value pairs of street, city, and postal, an array of hobbies and a key that is set to null because it's unknown for now if this person has pets.
Note that JSON doesn't have a built-in data type like Date or Symbol as we have in JavaScript.
JSON static methods
As mentioned earlier, in order to use JSON we need to convert it to JavaScript first. Even though they look similar, JavaScript objects are different and are not the same as JSON text format. Besides, objects have various built-in methods that help us to manipulate the data.
In order to work with JSON we need to use two built-in JavaScript methods. Information represented by JSON is a string as it is text-based data that is meant to be lightweight. That's why to work with the data we receive in the form of JSON we need to convert it to an object first.
JSON.parse
To convert JSON to JavaScript objects we can use a built-in method parse. This helps to "parse" the data and convert it into an object so we can do whatever we want with it using JavaScript. We might want to show this data on the website, convert it further into another object, update some data, or delete something from it. Very often you will find JSON when working with APIs however you can also create one yourself and store it locally.
Let's imagine we work with API and we receive a JSON that contains information about a person. We are going to use the JSON we created earlier. When we receive this data it's going to be represented in a string form. To convert it to a usable object we need to convert it to an object like so:
What will be the result in the console? It's going to be a JavaScript object.
What if we don't convert JSON? We will simply see a string that won't let us use object methods on it.
JSON.stringify
Sometimes we also need to do vice versa and convert a JavaScript object to JSON. To achieve that we can use another method stringify that converts an object to JSON. We use this when we want to send the data back to API. Another use case is localStorage or sessionStorarge where JSON is used. This time, let's create an object with the same data a convert it to JSON. Try to do it yourself first and remember the difference between JSON and JavaScript objects.
What will be the result in the console? A string representation of JSON that is ready to be sent to the database.
One thing to note here is that JSON doesn't have built-in date data types so be aware that when we convert Date type to JSON it will be converted to a string. The same applies to functions that will lose their "functionality" as strings so be careful with that.
JSON Array
When working with APIs we mostly work with objects however JSON can also be a simple array. Arrays are used when you need to use some order of elements and preserve the positions of these elements. JSON arrays can contain the same data types as JSON objects and can be parsed or stringified the same way.
How to use JSON with HTML?
When you are working with some data you most likely also need to display this data on the website. It can be done variously depending on what language you use or what framework or library but let's display some JSON data using Vanilla JavaScript. In this example, we are not going to work with any APIs but use a JSON file we have locally.
First, create two files - index.html and app.js. In the index file, we are going to display the data and in the app file, we will be working with this data. Usually, it's better to separate data from the functionality but let's add this data straight into the app file. Inside the HTML we will add the header and an empty section which will serve as a container for future data. Inside the JavaScript file, we can add the JSON data, parse this data, and log it to the console to make sure it's working.
Check your console and make sure that the data is correct and there are no errors. As you noticed, we used the parse method to make sure that JSON is converted to the JavaScript object so we can work with it. Now we can iterate over this data and show it in the HTML. To show it, we also need to create some additional elements that will hold this data and display all of it in the section that we have already created in the HTML file.
To target this section tag, we need to use an id of this element and in the JavaScript create a reference to this section.
In the console, you should be able to see our section HTML reference.
Next, we are going to start creating elements. For each person's data in the JSON, we are going to have an unordered list of the data. This means that we will iterate over each person, create a list of the data they contain, and add these items to the ul tag that we created.
First, we will iterate over the JSON array using forEach and then we will use for…in loop to iterate over the keys of an object of each person.
We need to remember that our object keys can be various data types including objects and arrays. In order to display the data properly, when we iterate over each key we will have to work with some values differently. You can directly display a string or number but if the key value is an object, you need to iterate over this object again as you cannot display an object directly. In our case, we will have three case scenarios. We will check if the key value is an array or if the value is an object to make sure we display the data properly.
Finally, we set all the values using innerHTML, append the created li tags to the ul tag, and then add it to the section tag.
As a result, our HTML page should display a list of all the keys and values.
For better results, you can also add names of your choice to the keys instead of using the original key names. You can also add other values conditionally if the key value is true or null, for example. You can also display only some parts of the data or display only specific objects that meet some criteria.
JSON versus others
JSON is obviously not the only popular data format and others are used just as much. Understanding how JSON compares to other data formats can help you to understand in what situation you need JSON or whether there are better options.
JSON vs XML
XML(Extensible Markup Language) is another data interchange format that is just as popular as JSON.
Syntax
While JSON has a similar syntax to JavaScript objects and uses key/value pairs, XML is more similar to HTML tags. It also has a hierarchy and may include more complex nested tags.
Data structure
JSON is mostly used when working with objects and arrays - APIs, configuration files, or the states for our application. XML however is used for more complex structures like document markup, more complex data interchange, or scientific data. However, you can of course use it for APIs as well, it's not forbidden.
Readability
JSON is considered to be more simple and more human-readable compared to XML as its syntax seems to be more complicated especially if it's very large. For every opening tag, you also need extra closing tags and this makes the text so much longer. On the other hand, if you have been using it for a while you might not notice that much complexity compared to very beginners.
Metadata
Metadata is an additional information or attribute that describes the main data. Things like origin, creation date, version, author, and so on. We can write metadata with JSON however it doesn't provide native mechanisms to embed metadata.
XML provides a possibility to add metadata structure and use additional data structure validations like Document Type Definitions (DTD) and XML Schema Definition (XSD). These are the methods to define the structure and validation rules for the XML document.
JSON vs CSV
CSV stands for comma-separated values and is another popular data interchange format.
Syntax
CSV is even more plain compared to JSON but this has its downsides as a result. CSV uses plain text of several lines. Each line represents a row of data while the first line represents the row name.
The columns can be separated by various delimiters like commas, tabs, semicolons, and pipe symbols. But note that the default delimiter is a comma and at times you might need to add additional logic if you want to use something else.
Data structure
CSV data is less useful for nested data like objects and arrays and is more suitable for flat data. We often use CSV for tabular data that is organized in rows and columns. Examples of such data can be employee information, product catalogs, or transactions. So if you want to use something more complex and nested, then CSV is not always the best choice.
Readability
Even though CSV might seem less complex it might also be a bit harder to read when there are a lot of rows and columns and it solely relies on delimiters.
Metadata
CSV does not support metadata either and it's also harder to implement it like it is in the case of JSON. That's why metadata is often managed separately.
JSONP
JSONP stands for JSON with Padding and is a special technique we use to transfer data while avoiding the same-origin policy limitations. The same-origin policy is a security feature used by web browsers that prevents making requests from any other places (domain, port, protocol) but the original one that serves the website. So, a page from abc.com cannot directly request data from def.com website using client-side JavaScript scripts. This protection helps to protect websites from malicious attacks and vulnerabilities. The origin is considered a URL combination of protocol (HTPP or HTPPS), domain, and port.
There are several ways to enable cross-origin requests and JSONP is one of them. What it does is that it runs the data as a script which makes data avoid the cross-origin restriction due to the fact that script tags are not restricted by cross-origin policy.
Usual JSON code uses a so-called "XMLHttpRequest" object when requesting files from another domain while JSONP uses a script containing a function call.
How to use JSONP?
For example, you want to retrieve data from https://website.com/api/data. You create a function which is a callback function to process the data you will receive in the future. Then, you create a script tag and for the value of the src tag you set the endpoint we mentioned above. At the end of this value, you add a query which is a callback function and this tells the server what function to use. Next, you append this script to the document that is executed when the document loads and the server returns the data wrapped in the callback function we wrote.
Why JSONP is a bad idea?
Even though it might sound tempting, JSONP is not recommended for use at all that's why I decided to cover it anyway. When there were no other workarounds it might have been a solution to something back in 2005 however in the modern world we have better solutions hence JSONP should be avoided. It makes our code vulnerable to XSS attacks as well as lacks proper error handling.
JSONP alternatives
There are several alternatives that you can use instead of JSONP.
- CORS(Cross-Origin Resource Sharing): Server-side configuration that helps to control access to resources from different domains by specifying which origin is permitted.
- Server-Side Proxies: You can set up proxies on the server that communicate with the requested resources on behalf of the client hence bypassing same-origin policy and offering more security.
- JWT (JSON Web Tokens) and OAuth: When sending data across various domains tokens are used to avoid exposing the user's credentials and grant access to third-party applications. This is another modern way to securely pass the data around. There are much more better alternatives so forget about JSONP.
Conclusion
Understanding JSON and its methods like parsing and stringification is important for effective data exchange and manipulation. Its simplicity and resemblance to JavaScript make it a very good choice especially when you're a beginner.
The comparison of JSON with other formats like XML and CSV is just as important as they have better usage in different situations. While JSONP used to be a workaround for cross-origin restrictions, there are more modern alternatives like CORS or server-side proxies, and token-based security mechanisms like JWT and OAuth.
Posted on November 10, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.