How to Read and Write to a JSON File in Python
JSON (JavaScript Object Notation) is a popular data exchange format based on a subset of JavaScript syntax. It is lightweight, human-readable, and easy to parse. Python, being a flexible and powerful language, has built-in support for JSON. In this article, we will learn how to read and write to a JSON file in Python.
Reading from a JSON File
Python has a built-in library called `json` that makes it easy to work with JSON data. We can use the `load` method from this library to read from a JSON file. Let’s say we have a JSON file named `data.json` with the following data:
“`json
{
“name”: “Alice”,
“age”: 30,
“hobbies”: [“swimming”, “reading”, “traveling”]
}
“`
We can read this file and extract the data as follows:
“`python
import json
with open(‘data.json’, ‘r’) as file:
data = json.load(file)
print(data[‘name’])
print(data[‘age’])
print(data[‘hobbies’])
“`
In this code, we first import the `json` library. Then, we use the `with` statement and the `open` function to open the file in read mode. We pass the file object to the `json.load` function, which reads the contents of the file and parses it into a Python dictionary. Finally, we print the values of the dictionary keys.
Writing to a JSON File
Similarly, we can use the `dump` method from the `json` library to write data to a new JSON file. Let’s say we have a Python dictionary with some data:
“`python
data = {
“name”: “Bob”,
“age”: 25,
“hobbies”: [“hiking”, “painting”, “coding”]
}
“`
We can write this data to a new JSON file named `newdata.json` as follows:
“`python
import json
with open(‘newdata.json’, ‘w’) as file:
json.dump(data, file)
“`
In this code, we again use the `with` statement and the `open` function to open the file in write mode. We pass the file object to the `json.dump` function along with the data dictionary. The `json.dump` function writes the dictionary to the file in JSON format.
Conclusion
In this article, we learned how to read from a JSON file using the `json.load` function and how to write to a JSON file using the `json.dump` function in Python. These functions make working with JSON data in Python easy and straightforward. With the `json` library, we can quickly parse JSON data into Python objects and manipulate them. We can also write Python objects to JSON format and store them in files.