Skip to main content

How to parse JSON data from a file in Python

How to parse JSON data from a file in Python.

Here's a step-by-step tutorial on how to parse JSON data from a file in Python.

Step 1: Import the Required Libraries

To parse JSON data in Python, we need to import the json library. Open your Python script or interactive shell and add the following line at the beginning:

import json

Step 2: Read the JSON File

Next, we need to read the JSON data from a file. In this example, let's assume we have a file named data.json in the same directory as our Python script. We can use the open() function to open the file and the json.load() function to load the JSON data.

with open('data.json') as file:
data = json.load(file)

Here, data will contain the parsed JSON data.

Step 3: Access the JSON Data

Now that we have the JSON data loaded into the data variable, we can access its contents. JSON data is typically represented as a nested structure of dictionaries and lists.

For example, let's assume our data.json file contains the following JSON data:

{
"name": "John Doe",
"age": 25,
"languages": ["Python", "JavaScript", "Java"],
"address": {
"street": "123 Main St",
"city": "New York",
"country": "USA"
}
}

To access the values, we can use standard Python syntax:

name = data['name']
age = data['age']
languages = data['languages']
address = data['address']

If the value is a nested dictionary or a list, we can continue accessing its contents in a similar manner:

street = address['street']
city = address['city']
country = address['country']

Step 4: Iterate Over JSON Lists

If the JSON data contains a list, we can iterate over its elements using a for loop. Let's assume our JSON data contains a list of books:

{
"books": [
{
"title": "Python Crash Course",
"author": "Eric Matthes"
},
{
"title": "JavaScript: The Good Parts",
"author": "Douglas Crockford"
}
]
}

We can iterate over the list and access each book's properties:

books = data['books']
for book in books:
title = book['title']
author = book['author']
print(f"Title: {title}, Author: {author}")

Step 5: Handle Errors

When parsing JSON data, it's essential to handle potential errors that may occur. If the JSON file is invalid or doesn't exist, an error will be raised.

To handle these errors, we can wrap our code in a try-except block:

try:
with open('data.json') as file:
data = json.load(file)
except FileNotFoundError:
print("JSON file not found!")
except json.JSONDecodeError:
print("Invalid JSON format!")

This way, we can gracefully handle errors and display appropriate messages to the user.

That's it! You now know how to parse JSON data from a file in Python. Remember to adjust the file name and JSON structure according to your specific use case.