JSON (JavaScript Object Notation) is a lightweight and widely-used data format for storing and exchanging information. Despite its name, JSON is language-independent and supported by many programming languages, including Python. In this tutorial, we'll explore how to work with JSON data in Python, from basic conversions to practical applications involving APIs.
Introduction to JSON
JSON structures data using key-value pairs and ordered lists, similar to dictionaries and lists in Python. Here's an example of JSON data:
{
"people": [
{
"name": "Alice",
"phone": "123-456",
"emails": ["[email protected]"],
"has_license": true
},
{
"name": "Bob",
"emails": null
}
]
}
Converting Between JSON and Python Objects
Python's built-in json
module allows easy conversion between JSON strings and Python objects.
1. Converting a JSON String to a Python Dictionary
Use json.loads()
to parse a JSON string into a dictionary:
import json
json_data = '''
{
"people": [
{
"name": "Alice",
"phone": "123-456",
"emails": ["[email protected]"],
"has_license": true
}
]
}'''
python_data = json.loads(json_data)
print(type(python_data)) # Output: <class 'dict'>
2. Converting a Python Object to a JSON String
Use json.dumps()
to serialize a dictionary into a JSON-formatted string. You can use indent
and sort_keys
for readable output:
# Remove the 'phone' key
for person in python_data['people']:
del person['phone']
new_json_string = json.dumps(python_data, indent=2, sort_keys=True)
print(new_json_string)
Working with JSON Files
1. Reading a JSON File
Use json.load()
to read and parse data from a file:
with open('states.json', 'r') as file:
data = json.load(file)
# Accessing the data
for state in data['states']:
print(f"{state['name']} ({state['abbreviation']})")
2. Writing to a JSON File
Use json.dump()
to save a dictionary to a file:
# Remove area codes
for state in data['states']:
del state['area_code']
with open('new_states.json', 'w') as file:
json.dump(data, file, indent=2)
Practical Example: Currency Exchange API Integration
Below is an example of consuming data from the ExchangeRate-API to convert USD to another currency:
import json
from urllib.request import urlopen
# Step 1: Fetch data from the API
url = "https://open.er-api.com/v6/latest/USD"
response = urlopen(url)
data_json = json.loads(response.read().decode('utf-8'))
# Step 2: Process the data
tusd_rates = data_json['rates']
# Convert USD to EUR
usd_value = 50
eur_value = usd_value * tusd_rates['EUR']
print(f"{usd_value} USD = {eur_value:.2f} EUR")
Explanation:
-
Fetching data: Uses
urlopen()
to make a request andjson.loads()
to parse the response. -
Processing: Extracts exchange rates from the
rates
dictionary. -
Conversion: Multiplies the dollar amount by the Euro rate.
Sample output:
50 USD = 45.83 EUR
Conclusion
JSON is essential for systems integration and API usage. Python's json
module makes it easy to work with JSON data, enabling smooth conversions between strings/files and Python objects. Practical applications range from system configurations to real-time data analysis via APIs.
Tip: Try exploring other public APIs (like Twitter or GitHub) to practice parsing and processing JSON data in real-world projects.
Commented Script: Create, Read, and Modify JSON Files
What this script does:
-
Creates a
states.json
file with sample data. -
Reads and prints state names and abbreviations.
-
Removes
area_code
from each state. -
Saves the modified data in
new_states.json
.
import json
# Step 1: Create 'states.json' with sample data
data_initial = {
"states": [
{"name": "São Paulo", "abbreviation": "SP", "area_code": 11},
{"name": "Rio de Janeiro", "abbreviation": "RJ", "area_code": 21},
{"name": "Minas Gerais", "abbreviation": "MG", "area_code": 31},
{"name": "Bahia", "abbreviation": "BA", "area_code": 71},
{"name": "Paraná", "abbreviation": "PR", "area_code": 41}
]
}
with open('states.json', 'w', encoding='utf-8') as f:
json.dump(data_initial, f, indent=2, ensure_ascii=False)
print("✅ File 'states.json' created successfully!\n")
# Step 2: Read and access data
with open('states.json', 'r', encoding='utf-8') as f:
data = json.load(f)
print("📄 States and Abbreviations:")
for state in data['states']:
print(f"{state['name']} ({state['abbreviation']})")
# Step 3: Remove area codes
for state in data['states']:
if 'area_code' in state:
del state['area_code']
with open('new_states.json', 'w', encoding='utf-8') as f:
json.dump(data, f, indent=2, ensure_ascii=False)
print("\n✅ File 'new_states.json' saved without area codes.")
Detailed Explanation of Parameters
Function / Parameter | Description |
---|---|
json.dump() |
Serializes a Python dictionary as JSON and writes to a file. |
indent=2 |
Adds 2-space indentation for better readability. |
ensure_ascii=False |
Ensures special characters (e.g., ç, ã) are saved properly. |
with open(...) as f |
Opens a file and ensures it’s properly closed after use. |
json.load() |
Reads and parses a JSON file into a Python dictionary. |
del state['field'] |
Deletes a key from a dictionary. |
Start experimenting with your own JSON data and APIs to unlock Python’s power in real-world applications!
Copyright Statement: Unless stated otherwise, all articles are original to this site, please credit the source when sharing.
Article link:http://pybeginners.com/python-libraries/working-with-json-data-in-python/
License Agreement:Attribution-NonCommercial 4.0 International License