JSON in Python

In this article, I will introduce you to JSON in Python. At the end of this article, you are going to learn what JSON is, why it exists, why people use it, and finally how to use the power of python for JSON.

As a data scientist, programmer, or even a machine learning practitioner, it’s important that you understand what JSON is and how to use it. I’m sure you’ll find plenty of applications there once you get the hang of it.

Also, Read – 9 Computer Vision Projects for Machine Learning.

What is JSON in Python?

JSON stands for JavaScript Object Notation and it’s a way to represent data. It follows a very simple and structured format that humans especially someone who knows the fundamentals of programming can easily understand. For example:

{
 "usersName": "amankharwal",
 "website": {
    "host": "www.medium.com",
    "account": "amankharwal",
    "blogpost": [
        {
            "type": "title",
            "description": {
                "main" : "82 Data Science & Machine Learning Projects",
                "sub" : "the info you need"
            }
        }
    ]
  }
}Code language: JSON / JSON with Comments (json)

Note how the code above is structured in key-value pairs, while still maintaining array objects. 

Why JSON?

It was introduced at the turn of the millennium to save us from Flash and Java applets. If you don’t remember these built-in browser plugins, consider yourself extremely lucky, because they are the nightmares. It was designed to provide a communication protocol between the real-time server and the stateless browser.

If you are already familiar with XML, you may want to consider using JSON as a lightweight, easier to use, and faster alternative.

Benefits:

It is believed that the first large company to start offering services and therefore popularize the adoption of JSON was Yahoo in 2005. It is now considered as the most widely used data format.

The top 3 benefits of using it are:

  • Very easy to read, write and handle
  • The transfer over the network is very fast
  • Supported by all major browsers, backend technology stacks

Fundamentals:

Storing data in a file

The code below encodes the data stored in d into JSON and stores it in a file (replace the filename with the actual filename):

import json
d = {
 'foo': 'bar',
 'alice': 1,
 'wonderland': [1, 2, 3]
}
with open(filename, 'w') as f:
 json.dump(d, f)Code language: JavaScript (javascript)

Retrieving data from a file

The code below opens a JSON encoded file (replace the filename with the actual filename) and returns the object stored in the file:

import json
with open(filename, 'r') as f:
  d = json.load(f)Code language: JavaScript (javascript)

Formatting Output:

Let’s say we have the following data:

 data = {"cats": [{"name": "Tubbs", "color": "white"}, {"name": "Pepper", "color": "black"}]}Code language: JavaScript (javascript)

Just unload this as JSONfile.dumps doesn’t do anything special here:

print(json.dumps(data))Code language: CSS (css)
{"cats": [{"name": "Tubbs", "color": "white"}, {"name": "Pepper", "color": "black"}]}

We can set the indentation to get the nicest output. If we want a nice print, we can set an indent size:

print(json.dumps(data, indent=2))Code language: PHP (php)
{
 "cats": [
 {
 "name": "Tubbs",
 "color": "white"
 },
 {
 "name": "Pepper",
 "color": "black"
 }
 ]
}

Sorting keys

By default, the order of keys in the output is undefined. We can get them alphabetically to make sure we always get the same result:

print(json.dumps(data, sort_keys=True))Code language: PHP (php)
{"cats": [{"color": "white", "name": "Tubbs"}, {"color": "black", "name": "Pepper"}]}

I hope you liked this article on the fundamentals of JSON in Python. Feel free to ask your valuable questions in the comments section below.

Also, Read – What is Transfer Learning?

Follow Us:

Aman Kharwal
Aman Kharwal

I'm a writer and data scientist on a mission to educate others about the incredible power of data📈.

Articles: 1435

Leave a Reply