JSON (JavaScript Object Notation) is a popular data interchange format that is easy for humans to read and write. JSON often comes into play when interacting with web APIs or HTTP requests within the field of programming. Python provides built-in support for working with JSON files through the json
module. In this article, we will discuss how to use Python to read, write, and manipulate JSON files.
To read a JSON file in Python, you can follow these steps:
json
module.open()
function with the mode set to r
.json.load()
function to load the contents of the file as a Python dictionary.Here is an example code snippet that demonstrates how to read a JSON file:
import json
# Open the JSON file
with open('data.json') as f:
data = json.load(f)
# Print the data (it will be stored as a Python dictionary)
print(data)
To write data to a JSON file in Python, you can use the json
module as well. Here are the steps to write data to a JSON file:
open()
function.json.dump()
function to write the dictionary data to the file in JSON format.Here is an example code snippet that demonstrates how to write data to a JSON file:
import json
# Define the data as a Python dictionary
data = {
'name': 'Bob',
'age': '25',
'city': 'Los Angeles'
}
# Write data to a JSON file
with open('output.json', 'w') as f:
json.dump(data, f)
You can read the output.json
file, modify the data dictionary by adding a new key-value pair, and then save it as another JSON file. Here's an example code snippet to achieve that:
# Read the data from the written file and print it
with open('output.json') as f:
output_data = json.load(f)
print(output_data)
# Modify the data by adding a new key-value pair
output_data['job'] = 'Engineer'
# Write the modified data to a new JSON file
with open('modified_output.json', 'w') as f:
json.dump(output_data, f)
# Read the modified data from the newly written file and print it
with open('modified_output.json') as f:
modified_data = json.load(f)
print('Modified data:', modified_data)
In this code snippet:
output.json
file.output_data
dictionary by adding a new key-value pair.modified_output.json
.modified_output.json
and print it.In conclusion, Python's json
module makes it simple to work with JSON files. You can read, write, and manipulate JSON data using Python's built-in functions, making it a powerful tool for handling JSON data in your Python projects.
Thank you for taking the time to explore data-related insights with me. I appreciate your engagement. If you find this information helpful, I invite you to follow me or connect with me on LinkedIn or X(@Luca_DataTeam). You can also catch glimpses of my personal life on Instagram, Happy exploring!👋