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.
- String
- Number
- Object (JSON object)
- Array
- Boolean
- null
When these data types are converted in python for reading they are converted to python equivalent data type according to the following table:
Python | JSON equivalent |
dict | object |
list, tuple | array |
str | string |
int, float | number |
True | true |
False | false |
None | null |
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) 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.
Output:
{‘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) print(student_loaded) print(student_loaded['subject'])
Output:
{‘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(student_dumped) 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”]}
<class ‘str’>
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.
No comments:
Post a Comment