How do you read and write JSON data in Python?
This article provides a step-by-step guide to reading and writing JSON data using Python. …
Updated August 26, 2023
This article provides a step-by-step guide to reading and writing JSON data using Python.
JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write, and easy for machines to parse and generate. It’s become the standard way to transmit data between web servers and applications. Because of its ubiquity, knowing how to work with JSON in Python is essential for any aspiring developer.
Here’s why this question is so important for learning Python:
Web Development: Many APIs (Application Programming Interfaces) return data in JSON format. Understanding how to read and process this data is crucial for building web applications that interact with external services.
Data Science: JSON is often used to store configuration files and structured data sets. Being able to read and write JSON allows you to load data into your Python programs for analysis and manipulation.
File Storage: JSON provides a human-readable way to store data in files, making it ideal for settings, preferences, and other structured information.
Python’s built-in json
module makes working with JSON data incredibly straightforward.
Here’s a step-by-step guide:
1. Reading JSON Data
Let’s say you have a JSON file named “data.json” containing the following:
{
"name": "Alice",
"age": 30,
"city": "New York"
}
Code:
import json
with open('data.json', 'r') as f:
data = json.load(f)
print(data['name']) # Output: Alice
print(data['age']) # Output: 30
print(data['city']) # Output: New York
Explanation:
- We import the
json
module. - We open the “data.json” file in read mode (
'r'
). - The
json.load(f)
function reads the JSON data from the file and converts it into a Python dictionary. - We can then access values in the dictionary using their keys (e.g.,
data['name']
).
2. Writing JSON Data
Let’s say we have a Python dictionary we want to save as JSON:
person = {
"name": "Bob",
"age": 25,
"city": "Los Angeles"
}
Code:
import json
with open('new_data.json', 'w') as f:
json.dump(person, f)
Explanation:
- We import the
json
module. - We open a new file “new_data.json” in write mode (
'w'
). - The
json.dump(person, f)
function takes the Python dictionary (person
) and writes it to the file as JSON formatted data.
Important Notes:
- Indentation: When writing JSON, the output will be automatically indented for readability. You can control the indentation level using the
indent
parameter injson.dump()
. - Data Types: Python dictionaries map well to JSON objects. Lists are converted to JSON arrays. Other data types like strings, numbers, booleans, and
None
are represented directly in JSON.
Let me know if you have any other questions!