Reading a JSON File in Python

Mahabubur Rahman

The full form of JSON is Javascript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the JSON package in Python script. The text in JSON is done through quoted-string which contains the value in key-value mapping within { }. It is similar to the dictionary in Python.

Reading JSON from a file using Python

Deserialization is the opposite of Serialization, i.e. conversion of JSON objects into their respective Python objects. The load() method is used for it. If you have used JSON data from another program or obtained it as a string format of JSON, then it can easily be deserialized with load(), which is usually used to load from a string, otherwise, the root object is in a list or Dict. 

Reading JSON from a file using  json.load() 

The JSON package has json.load() function that loads the JSON content from a JSON file into a dictionary. It takes one parameter:

File pointer: A file pointer that points to a JSON file.

# Opening JSON file
with open('file.json', 'r') as openfile:
# Reading from json file
json_object = json.load(openfile)

For JSON Object


{'name': 'Rafi Hasan', 'rollno': 56, 'cgpa': 8.6, 'phone': '01532323232'}

<class 'dict'>

For JSON Array

[{'name': 'Rafi Hasan', 'rollno': 56, 'cgpa': 8.6, 'phone': '01532323232'},
{'name': 'Rafiul Ramzan', 'rollno': 57, 'cgpa': 8.6, 'phone': '01362323232'}]

<class 'list'>


Post a Comment

Post a Comment (0)