Python JSON Reading and Writing Operations
You can use the json module to read and write JSON files in Python. First, you need to import the json module into your project.
import json
Then, you can use the json.load() function to read a JSON file and the json.dump() function to write. As an example, the following code snippet reads a JSON file and prints its contents:
import json
# Open the JSON file
with open('data.json', 'r') as f:
# Load the file
data = json.load(f)
# Print the loaded data
print(data)
Similarly, you can use the following code snippet to write a Python data structure to a JSON file:
import json
# Data to write
data = {'name': 'John Smith', 'age': 30, 'city': 'New York'}
# Open the JSON file
with open('data.json', 'w') as f:
# Write the data to the file
json.dump(data, f)
In these examples, a file called data.json is created, and data is written to this file. By changing the file name and path as you wish, you can read and write different files.
Note: The json.load() function only reads JSON files. If you want to read the data as a Python data structure, you can use the json.loads() function. Similarly, the json.dump() function only writes to files, while the json.dumps() function returns a Python data structure as a string.
Yorum Gönder