JSON has nowadays, become the standard for the exchange of information. It is particularly in use to store data and also extract meaningful data. You need to know how the process of extracting data from JSON files, because you might be sometimes, working to gather information using an Application Programming Interface (API) or maybe putting your data safe into a database. That is to say, you’ve no way to get away from JSON data, but don’t worry, Python is here as a help.

We are here, therefore, going to learn all the tricks that we need up our sleeves to work with JSON data.

BRIEF INTRODUCTION

JSON or JavaScript Object Notation is a very popular data standard used for exchanging information and also for representing structured data. It has become a common norm to transfer data in JSON format during exchange with client-server or web applications.

JSON forms the most common standard for data stored in web applications

As a standard it is also very common to store JSON objects in a file.

JSON is there like a string in Python. As in:

S = '{"credentials": "Shubham", "programming": ["C", "Python", "R" ]}'

Well that looks like a Python dictionary only for me to say, “NO” it’s not actually a Python dictionary but is somewhat similar to it in notations.

WORKING WITH JSON

While working with JSON in Python, we need to do certain tasks. These tasks I will hence, discuss below :

Importing the “json” Module

In order to, work with JSON data (string, or file containing JSON object), one can utilize Python’s json module. To do this one needs to first import the “json” module before utilizing the same.

#Importing the "JSON" module
import json

Now to — Parse JSON data

The json module eases the ability to parse JSON data files and strings that contain JSON objects.

For Parsing JSON data, Python makes use of the loads function from the json module to load the JSON data stored in a string. Python, for instance, treats JSON data as a string until it’s fetched from a file.

Example :

parsed = (json.loads(json_info))
print(json.dumps(parsed, indent=5, sort_keys=False))

One can even save the extracted data to a variable also and iterate over it to get all values and see.

loaded = json.loads(json_info)
for a in loaded:
	print(" %s: %d " % (a, loaded[a]))

It is then seen that, loaded has a dictionary and not a string.

Parsing JSON data to Dictionary

Complete Example :

import json

det = '{"Credentials": "Shubham", "programming": ["C", "Python"]}'
det_dict = json.loads(det)

# To Output the full details
print(det_dict)

# To Output only the programming languages information
print(det_dict['programming'])

Hence, det is a JSON string, and det_dict is a dictionary, here.


Reading a JSON file in Python

One makes use of the already discussed json.load() function to read and load data from a file containing JSON object.

Shown below is the way to parse the file named det.json which containing JSON objects.

import json

with open('File_path/det.json') as file:
  info = json.load(file)

# To Output the data
print(data)

The open() method is used to read the information from the json file. When we use the  json.load() function it fetches a dictionary named info.

Converting Dictionary Data to a JSON String

One can easily change a dictionary data into a JSON string using the json.dumps() function.

import json

det_dict = {'Credentials': 'Shubham',
'Age': 25,
'Education': "Graduation"
}
det_json = json.dumps(det_dict)

# Output :
print(det_json)

JSON Equivalents of Different Python Objects :

PythonJSON Equivalent
dictobject
list, tuplearray
strstring
int, float, intnumber
Nonenull
JSON Equivalents of Different Python Objects

Parsing JSON data into an Object

JSON is in reality, an object type notation in JavaScript, so it definitely makes sense to import it as an object. So, there are various ways and methods to do this.

One way is by loading the JSON data into the __dict__ property of an object. Thus,

class Sample(obj):
    def __init__(self, info):
	    self.__dict__ = json.loads(info)

Sample1 = Sample(json_info)
print(Sample1.x)

Extracting data from JSON and Writing in File

For this task, one uses the json.dump() function.

# importing the json module
import json

det_dict = {"Credentials": "Shubham",
"programming": ["C", "Python"],
"age": 25 }

# Loading data into a File from JSON Data
with open('det_dict.txt', 'w') as file:
   json.dump(det_dict, file)

Here, a file with the name  det_dict.txt is opened in writing mode with  'w'. Then, json.dump() converts the det_dict to JSON string to be saved in the det_dict.txt file.

Output :

{"Credentials": "Shubham", "programming": ["C", "Python"], "age": 25}

Extracting Data from JSON

The various steps shown in these examples show a similar pattern or template that is followed during the process of extracting data from a JSON file.

  • First and foremost we bring in  the json module.
  • Secondly, we read the data with the loads()  method.
  • Then, the processing of the information is done.
  • And finally, the converted data is written using the dump() method.

All good things come to an end!

As a result of this post, I hope to have made you realize and generate the power of JSON for your Python endeavors and requirements. .

The various examples shown here are very nicely curated and engineered and made equally easier and simpler. Also, they are here to give you a certain workflow template. Generally, the above template can be utilized in every task of yours.

Thus, now, it is all dependent on you as to what you do with the data you have extracted and loaded into the memory. Hence, it is now all unto you to make what you want out of it, based on your requirements.

The usual route is, gathering the data, followed by extracting meaningful insight, and processing or storing the data for further use.

Thus, hoping to have inspired you for your future tasks. Also, wishing you all the best for future endeavors. Hence, Ta-Ta !!!

Categorized in: