If you’ve ever worked with APIs, web applications, or configuration files, you’ve probably come across JSON. JSON stands for JavaScript Object Notation, and it's a popular data format used for storing and exchanging information between a server and a client.
In this blog post, we’ll take a friendly walk through how to work with JSON files in Python.
What is JSON?
JSON is a lightweight data format that is easy for humans to read and write, and easy for machines to parse and generate. It’s based on key-value pairs, similar to Python dictionaries.
Here’s a small JSON snippet:
{
"name": "Ayush",
"age": 29,
"skills": ["Python", "Django", "JavaScript"]
}
Why Use JSON in Python?
Python has a built-in module called json
that makes it super easy to work with JSON data. With this module, you can:
-
Convert JSON data to Python objects
-
Convert Python objects to JSON
-
Read JSON from a file
-
Write JSON to a file
Let’s dive into each of these.
Reading JSON Data (From a String or a File)
Let’s start by learning how to load JSON data into Python.
Reading JSON from a string
import json
# JSON string
json_data = '{"name": "Ayush", "age": 29, "city": "Delhi"}'
# Convert JSON string to Python dictionary
data = json.loads(json_data)
print(data)
print(data['name']) # Output: Ayush
json.loads()
is used to convert a JSON string into a Python dictionary.
Reading JSON from a file
If your JSON is in a file (which is common), you can use json.load()
.
Example: data.json
file
{
"name": "Ayush",
"age": 29,
"city": "Delhi"
}
Python Code:
import json
# Open the file and load JSON data
with open('data.json', 'r') as file:
data = json.load(file)
print(data)
print(data['city']) # Output: Delhi
Writing JSON Data (To a String or File)
Now let’s see how to convert Python objects into JSON and write them to files.
Convert Python to JSON string
import json
# Python dictionary
person = {
"name": "Ayush",
"age": 29,
"skills": ["Python", "Django"]
}
# Convert Python dict to JSON string
json_string = json.dumps(person)
print(json_string)
json.dumps()
is used to convert Python objects to JSON strings.
Writing JSON to a file
import json
# Dictionary
person = {
"name": "Ayush",
"age": 29,
"skills": ["Python", "Django"]
}
# Write JSON data to file
with open('person.json', 'w') as file:
json.dump(person, file)
print("Data written to file successfully.")
json.dump()
writes Python objects directly to a JSON file.
Making JSON Output Pretty
When you dump JSON, you might want it to be more readable. You can do this by using the indent
and sort_keys
options.
import json
person = {
"name": "Ayush",
"age": 29,
"skills": ["Python", "Django"]
}
# Pretty print JSON to file
with open('person_pretty.json', 'w') as file:
json.dump(person, file, indent=4, sort_keys=True)
This will save the file like:
{
"age": 29,
"name": "Ayush",
"skills": [
"Python",
"Django"
]
}
Common Operations with JSON in Python
Update a value in JSON file
You can load a JSON file, change its value, and write it back.
import json
# Load existing JSON
with open('person.json', 'r') as file:
data = json.load(file)
# Update value
data['age'] = 30
# Save updated data
with open('person.json', 'w') as file:
json.dump(data, file, indent=4)
Add a new key-value pair
data['email'] = 'ayush@example.com'
with open('person.json', 'w') as file:
json.dump(data, file, indent=4)
Handling JSON Arrays
JSON arrays are just like Python lists. Here’s how you handle them.
[
{
"name": "Ayush",
"age": 29
},
{
"name": "Ravi",
"age": 25
}
]
Read this in Python:
import json
with open('people.json', 'r') as file:
people = json.load(file)
for person in people:
print(person['name'])
Real-World Use Case Example
Let’s say you’re building a simple contacts manager. You want to save and load contacts using JSON.
Saving Contacts:
import json
contacts = [
{"name": "Ayush", "phone": "1234567890"},
{"name": "Ravi", "phone": "9876543210"}
]
with open('contacts.json', 'w') as file:
json.dump(contacts, file, indent=4)
Loading and displaying contacts:
import json
with open('contacts.json', 'r') as file:
contacts = json.load(file)
for contact in contacts:
print(f"Name: {contact['name']}, Phone: {contact['phone']}")
Common Errors and Tips
-
JSONDecodeError: Happens when your JSON string/file is not properly formatted.
-
Always use
with open()
for file operations – it automatically closes the file. -
JSON keys must be in double quotes (
"key"
), not single quotes.
Final Thoughts
If you’re learning Python or working on real-world projects, you’ll come across JSON everywhere. Mastering JSON operations will make your life easier when dealing with data exchange or persistent storage in your apps.