Let's consider the following data:
[
{
"name": "John Doe",
"age": 30,
"department": "Engineering",
"title": "Software Engineer"
},
{
"name": "Jane Smith",
"age": 25,
"department": "Marketing",
"title": "Marketing Specialist"
}
]
To load and work with this JSON data in Python, follow these steps:
Import the JSON Module
First, import the json module, which provides functionalities to parse JSON strings and convert them into Python objects.
import json
Load JSON Data from a File
Assume the JSON data is saved in a file named employees.json.
👉 You can crate a new .json file and copy-paste the data above to create that file.
Use the open() function to read the file, and the json.load() function to parse the JSON data.
with open('employees.json', 'r') as file:
employees = json.load(file)Accessing the Data
Once the JSON data is loaded, it is converted into a Python list of dictionaries, allowing you to access and manipulate the data easily.
for employee in employees:
print(f"Name: {employee['name']}, Age: {employee['age']}, Department: {employee['department']}, Title: {employee['title']}")
Here is a complete example that demonstrates loading and accessing the JSON data:
import json # Load JSON data from a file
with open('employees.json', 'r') as file:
employees = json.load(file) # Access and print employee details
for employee in employees:
print(f"Name: {employee['name']}, Age: {employee['age']}, Department: {employee['department']}, Title: {employee['title']}")
This simple script reads employee data from a JSON file and prints each employee's details. Using Python's json module makes it straightforward to parse and work with JSON data.
Practice what you just learned
Solve Python exercises and get instant AI feedback on your solutions.
Try ActiveSkill for Free →
Python Mega Course: Learn Python in 60 Days, Build 20 Apps
Learn Python on Udemy completely in 60 days or less by building 20 real-world applications from web development to data science.
