How to Read and Write to JSON File in Python

Spread the love

In this tutorial we will go through the process of reading and writing JSON files in Python. While sending or receiving data between server it can only be text, so JSON (JavaScript Object Notation) is a data format used to convert JavaScript object to JSON and send it to the server.
Python has a module json which is used in doing manipulation on json files and for creating new json files. While working with Python json files exist as a string, that means anytime we are working with Python every json file is considered as a string. In JSON, variables must be of one of the following data types.
Object (JSON object)
When these data types are converted in python for reading they are converted to python equivalent data type according to the following table: 
JSON equivalent
list, tuple
int, float
Reading JSON File in Python
For reading json file in python we can use the json.loads() method from json module. Here is a simple example : import json
student = ‘{“name”: “Rajesh”, “roll” : “52”, “subject”: [“English”, “Science”]}’
student_loaded = json.loads(student)
print(student_loaded[‘roll’])Here the student string is representing the json object which is getting converted into a python dictionary according to the above table.
{‘name’: ‘Rajesh’, ‘roll’: ’52’, ‘subject’: [‘English’, ‘Science’]}52
Here we have taken the json file in a python string which is not used practically, In practice we will read json file, so while reading instead of using the method loads method load is used to convert json into python.
Now if our student.json file looks something like this {
“name”: “Rajesh”,
“roll” : “52”,
“subject”: [“English”, “Science”]
}Then to read this file the python code will look like:import json

with open(‘student.json’) as json_file :
student_loaded = json.load(json_file)

{‘name’: ‘Rajesh’, ‘roll’: ’52’, ‘subject’: [‘English’, ‘Science’]}[‘English’, ‘Science’]
Writing to JSON File in Python
The same table will now be used to convert python data types to json equivalents. To convert a python dict to a json object we will use the method dumps from the json module. It will return a string which will be converted into json format. The python code looks as below: import json

student = {
‘name’: ‘Rajesh’,
‘roll’: 52,
‘subject’: [‘English’, ‘Science’]

student_dumped = json.dumps(student)

print(type(student_dumped))In the above code the student is a dictionary and the result after performing the dumps operation is a string which is evident from the output.
{“name”: “Rajesh”, “roll”: 52, “subject”: [“English”, “Science”]}
As in the case of loads, while writing to a json file instead of using dumps we simply use dump for the same.import json

student = {
‘roll’: 52,
‘name’: ‘Rajesh’,
‘subject’: [‘English’, ‘Science’]

with open(‘student.json’,’w’) as student_dumped :
json.dump(student,student_dumped)This will create(if not present) or modify the student.json file to:
{“roll”: 52, “name”: “Rajesh”, “subject”: [“English”, “Science”]}
In the dump method the first is the python dict and second is the python file as argument. As we can see in the above output, dump does not write file in readable format. We can use parameters in the dump method to make it more readable.
indent: used for indentation in json file 
sort_keys: used for sorting keys in ascending order.
By default indent value is None and sort_keys is False.import json

student = {
‘roll’: 52,
‘name’: ‘Rajesh’,
‘subject’: [‘English’, ‘Science’]

with open(‘student.json’,’w’) as student_dumped :
json.dump(student,student_dumped,indent = 4,sort_keys = True)Using the above parameters the output is changed to:
{    “name”: “Rajesh”,    “roll”: 52,    “subject”: [        “English”,        “Science”    ]}
I hope you got idea about how to read and write to json file in python. Comment down below if still you have any queries.
The post How to Read and Write to JSON File in Python appeared first on The Crazy Programmer.

X ITM Cloud News


Next Post

GitHub Finally has Launched its Mobile App

Sun Nov 24 , 2019
Spread the love          Microsoft acquisition “GitHub” has news from their cosmos to give more than 40 million developers and contributors a reason to celebrate. Undoubtedly, 2018 has been a favorite year for developers with the expansion of the open-source community (GitHub), adding up approx. 10 million new users from around 70 countries and […]

Cloud Computing – Consultancy – Development – Hosting – APIs – Legacy Systems

X-ITM Technology helps our customers across the entire enterprise technology stack with differentiated industry solutions. We modernize IT, optimize data architectures, and make everything secure, scalable and orchestrated across public, private and hybrid clouds.

This image has an empty alt attribute; its file name is x-itmdc.jpg

The enterprise technology stack includes ITO; Cloud and Security Services; Applications and Industry IP; Data, Analytics and Engineering Services; and Advisory.

Watch an animation of  X-ITM‘s Enterprise Technology Stack

We combine years of experience running mission-critical systems with the latest digital innovations to deliver better business outcomes and new levels of performance, competitiveness and experiences for our customers and their stakeholders.

X-ITM invests in three key drivers of growth: People, Customers and Operational Execution.

The company’s global scale, talent and innovation platforms serve 6,000 private and public-sector clients in 70 countries.

X-ITM’s extensive partner network helps drive collaboration and leverage technology independence. The company has established more than 200 industry-leading global Partner Network relationships, including 15 strategic partners: Amazon Web Services, AT&T, Dell Technologies, Google Cloud, HCL, HP, HPE, IBM, Micro Focus, Microsoft, Oracle, PwC, SAP, ServiceNow and VMware