JSON 101
The world needs data interchange formats like XML and JSON, to exchange data between very different systems. Portability, or the compatibility in transferring information between platforms and systems, is the very goal of a data interchange format.
| Prerequisites
- Basic understanding of various Programming Paradigms.
- Familiarity with JavaScript and Python syntax.
1 | Introducing JSON
JSON stands for ‘JavaScript Object Notation’. It is also known as ‘Data Interchange Format’ as it is used to store and exchange the data.
Properties of JSON
- Based on the object literal notation of JavaScript.
- Language independent.
- Have support in all popular programming languages.
- Organized and Easy-to-access.
The spirit of a data interchange format is to be independent of language.
Why is JSON more preferred data interchange format compared to XML nowadays?
JSON has a more human-readable format, compared to the XML. Where XML uses a whole lot of opening and closing tags, JSON simply uses {} for objects, [] for arrays, and this makes it much more lightweight. This, in turn, results in faster processing and transmission.
2 | JSON Syntax
Let’s have a quick look at the basic syntax of JSON. JSON syntax is basically considered as a subset of JavaScript syntax. It includes the following −
- Data is represented in key-value pairs.
- Curly braces({…}) hold objects.
- Each key is followed by a colon(:).
- The key-value pairs are separated by a comma(,).
- Keys and string values must be enclosed in double quotes(“…”).
- Square brackets([…]) hold arrays and values are separated by a comma.
Below is a simple example —
{
"book": [
{
"id": 2,
"language":"JSON",
"title":"Introduction to JSON"
"author":"Lindsay Bassett"
},
{
"id":5,
"language":"Python",
"title":"Introduction to Python"
"author":"Bill Lubanovic"
}
]
}
You can even place an apostrophe in the keys — “Darshan’s animal”:“dog”
. But the key-value pairs used in JSON, when loaded in memory by a system as an object, will become a “property” or “attribute”. Having space or special character (other than A-Z, a–z, 0–9) in the key, would not be taking portability into consideration. This could decrease portability; therefore, it is important to avoid spaces or special characters in keys for maximum portability. Instead, you can use Camel Case — “darshansAnimal”:“dog”
.
3 | JSON Data Types
Here’s the list of all the data types for the values that can be used to represent data in JSON —
- number
- string (in double quotes)
- boolean (true or false)
- null
- object
- array
Below is a very basic example which utilizes all the data types —
{
"first-name":"Darshan",
"last-name":"Majithiya",
"age":20,
"married":false,
"experience":null,
"programmingLanguages":["Python", "JavaScript", "PHP", "SQL"],
"education":{
"college":"GCET",
"school":"St. Xavier's High School"
}
}
4 | Serialization, Deserialization, and Requesting JSON data on the Client side
It’s pretty common for websites to return JSON from their APIs as it’s very easy to parse. Take a look at the below code —
var myXMLHttpRequest = new XMLHttpRequest();
var url = VALID_URL_TO_REQUEST_THE_JSON_DATA_FROM;myXMLHttpRequest.onreadystatechange = function() {
if (myXMLHttpRequest.readyState === 4 && myXMLHttpRequest.status === 200) {
var myObject = JSON.parse(myXMLHttpRequest.responseText);
var myJSON = JSON.stringify(myObject);
}
}myXMLHttpRequest.open(“GET”, url, true);
myXMLHttpRequest.send();
- The first line shows the creation of the XMLHttpRequest object. Though the JavaScript XMLHttpRequest sound like it has to do with XML. However, XMLHttpRequest is not restricted to XML. We use it to request JSON despite its name. It uses HTTP protocol to request the data.
- The second line shows the assigning of valid URL from which we can request the data. Generally, this URL is a combination of SERVER_ADDRESS, WEB_API_KEY, and REQUESTED_DATA.
- Then we’ve created a function and assign it to the onreadystate‐ change property of myXMLHttpRequest. This function will be executed every time the readyState property changes. In the function, check to see if the readyState is 4 (code for “done”) and that the HTTP status is 200 (code for success). If both of those things are true, then parse the JSON into a JSON object.
- Two terms that you will often hear about when JSON is turned into the text from an object and then from an object back into the text are serialization and deserialization. Serialization is the act of converting the object into text. Deserialization is the act of converting the text back into an object.
- When we receive data from a web server, the data is always a string. In the JavaScript, deserializing is done with
JSON.parse()
. - When sending data to a web server, the data has to be a string. In the JavaScript, Serializing is done with
JSON.stringify()
. XMLHttpRequest.open()
initializes a newly-created request, or re-initializes an existing one andXMLhttpRequest.send()
sends the request to the server. If the request is asynchronous (which is the default), this method returns as soon as the request is sent and the result is delivered using events. If the request is synchronous, this method doesn’t return until the response has arrived.
5 | Serialization, Deserialization, and Requesting JSON data on the Server side
The success of a data interchange format on the Web requires support on both the client and server side. If we were to have support on the client side, but not the server side, JSON would be dead in the water. Fortunately, JSON is widely supported by most server-side web frameworks or scripting languages. If they do not have built-in support for serializing and deserializing JSON, it is likely that a library or extension exists to support it.
We’ll be using Python to demonstrate the implementation on Server Side. Take a look at the below code —
import requests
import jsonresponse = requests.get(VALID_URL_TO_GET_THE_JSON_DATA_FROM)
if response.status_code == 200:
'''converts JSON data into appropriate Python object'''
load_content = json.loads(response.text)'''converts Python object into JSON'''
dump_content = json.dumps(load_content)
- First, we import the necessary libraries — requests and json. (You can also use urllib.request library instead of requests.)
- Then we request data from a valid URL by making an HTTP GET request using
requests.get()
. (You can also make an HTTP POST request usingrequests.post()
.) response.status_code()
check whether the request is successful or not.
json.loads()
deserializes the JSON data into an appropriate Python object. (Check the image 1 to see how different JSON datatypes are converted in python)json.dumps()
serializes the Python object into JSON formatted stream.
There are various functions in both, requests and json, libraries that you can use to perform read/write operations on .json files. You can read about them on python-requests and json — python. For experimenting with the code you can use this URL — https://api.github.com/events
The file extension for JSON is easy to remember: .json. The MIME type for JSON is application/json.
| Conclusion
The focus of this article has been on interchanging data between two parties using JSON. As a configuration file sitting on a server, or a resource being requested by a URL, JSON is doing a great job as a data interchange format.
And now more than ever before, it is important to be familiar with JSON because a vastly used document-oriented NoSQL database reads and writes data formatted in JSON — which is the de facto standard for consuming and producing data. Even in data science, JSON is a widely accepted format for sharing structured data between applications and data scientists whenever possible.
| References
I’ve referred to below sources for learning JSON and also, to write this article. Why don’t you take a look at them?. They are wonderful. :)
- Lindsay Bassett’s Introduction to JavaScript Object Notation
- JSON in Action — Udemy
- XMLHttpRequest — MDN web docs
- Working with JSON Data using the json Module — YouTube
If you enjoyed this article, feel free to clap many times (you know you want to!) and share with a friend. You can also leave a comment to ask a question or tell me how to improve. :)
Darshan Majithiya is a final year IT engineering student. I’m passionate about Data Science and Web Development. I believe Data and memorable User Experience are two of the most important pillars of any intelligent product. Connect with me on LinkedIn or say hi on Twitter.