visit
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.
json
module.open()
function with the mode set to r
.json.load()
function to load the contents of the file as a Python dictionary.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.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.