How to Read a JSON File Using Python – A Complete Guide

Working with structured data has become an essential part of software development, web applications, and data analysis. One of the most common formats for storing and exchanging data is JSON (JavaScript Object Notation). If you’re learning Python or building applications that involve APIs, databases, or configuration files, chances are you’ll come across JSON sooner rather than later.

In this detailed guide, we will cover:

  • What JSON is and why it’s widely used.

  • How Python handles JSON through its built-in json module.

  • Different methods to read JSON files in Python.

  • How to access and manipulate JSON data once it’s loaded.

  • Writing JSON back to files in Python.

  • Common mistakes and troubleshooting tips.

  • Alternatives if you don’t have Python installed.

By the end of this article, you’ll be confident in handling JSON files like a pro.

What is JSON and Why is it Important?

JSON (short for JavaScript Object Notation) is a lightweight, text-based data interchange format. Despite its origins in JavaScript, JSON is language-independent and supported in almost every modern programming language, including Python, Java, C#, Ruby, and more.

Some of the reasons JSON is so popular:

  1. Human-readable – It looks clean and simple, making it easy for developers to read.

  2. Lightweight – Smaller in size compared to XML or other formats.

  3. Easy to parse – Can be quickly converted into native objects like dictionaries in Python.

  4. Universal – Widely used in APIs, web services, mobile apps, and configuration files.

  5. Flexible – Handles complex, nested structures with arrays and objects.

Example JSON snippet:

{
“employees”: [
{
“id”: “1”,
“firstName”: “Tom”,
“lastName”: “Cruise”
},
{
“id”: “2”,
“firstName”: “Maria”,
“lastName”: “Sharapova”
},
{
“id”: “3”,
“firstName”: “James”,
“lastName”: “Bond”
}
]
}

JSON and Python: A Perfect Match

Python provides a built-in module called json, which makes working with JSON seamless. The JSON format maps very closely to Python’s built-in data structures:

  • JSON objects → Python dictionaries

  • JSON arrays → Python lists

  • JSON strings → Python strings

  • JSON numbers → Python integers/floats

  • JSON true/false → Python True/False

  • JSON null → Python None

This natural mapping means you don’t need extra libraries to start working with JSON in Python.

How to Read a JSON File in Python

The most common task with JSON is reading it into your program. Python provides two main ways:

  1. Reading directly from a JSON file (json.load())

  2. Reading from a JSON string (json.loads())

Let’s look at each method in detail.

Method 1: Reading JSON from a File

Suppose we have a file called employees.json with the following content:

{
“employees”: {
“employee”: [
{“id”: “1”, “firstName”: “Tom”, “lastName”: “Cruise”},
{“id”: “2”, “firstName”: “Maria”, “lastName”: “Sharapova”},
{“id”: “3”, “firstName”: “James”, “lastName”: “Bond”}
]
}
}

Here’s the Python code to read this file:

import json

# Open and load the JSON file
with open(“employees.json”, “r”) as file:
data = json.load(file)

# Print the loaded data
print(json.dumps(data, indent=2, sort_keys=True))

Explanation:

  • with open("employees.json", "r") – Safely opens the file in read mode.

  • json.load(file) – Reads the JSON file and parses it into a Python dictionary.

  • json.dumps(data, indent=2, sort_keys=True) – Converts the dictionary back to a formatted string for pretty printing.

Method 2: Reading JSON from a String

Sometimes, you don’t have a file but instead get JSON data as a string (for example, from an API response). In such cases, use json.loads().

import json

json_string = ‘{“name”: “Alice”, “age”: 30, “city”: “New York”}’

# Parse JSON string into a Python dictionary
data = json.loads(json_string)

print(data)

Output:

{'name': 'Alice', 'age': 30, 'city': 'New York'}

Accessing JSON Data in Python

Once you load JSON into Python, you can navigate it just like dictionaries and lists.

Example:

for emp in data["employees"]["employee"]:
print(emp["firstName"], emp["lastName"])

Output:

Tom Cruise
Maria Sharapova
James Bond

This shows how you can iterate through arrays inside JSON.

Writing JSON to a File in Python

Reading JSON is just one side of the coin. You often need to write data back into JSON. Python’s json.dump() makes this easy.

import json

employee = {
“id”: “4”,
“firstName”: “Robert”,
“lastName”: “Downey”
}

with open(“new_employee.json”, “w”) as file:
json.dump(employee, file, indent=2)

This creates a file new_employee.json with:

{
“id”: “4”,
“firstName”: “Robert”,
“lastName”: “Downey”
}

Pretty Printing JSON

If you want your JSON output to look clean and readable, use json.dumps() with indent.

print(json.dumps(data, indent=4))

This makes the structure easier to debug and understand.

Handling Errors While Reading JSON

Sometimes, JSON data may be corrupted or invalid. Common errors include:

  1. json.decoder.JSONDecodeError – Raised when JSON syntax is invalid.
    Example: missing quotes or commas.

  2. File not found – If the JSON file path is incorrect.

  3. Encoding issues – Some JSON files may use UTF-8, UTF-16, etc.

To avoid crashes, wrap your code in a try-except block:

try:
with open(“employees.json”, “r”, encoding=”utf-8″) as file:
data = json.load(file)
except FileNotFoundError:
print(“File not found. Please check the file path.”)
except json.JSONDecodeError:
print(“Invalid JSON format. Please validate your file.”)

Real-World Use Cases of JSON in Python
  1. Web APIs – Almost every modern API returns data in JSON. Python libraries like requests make it simple to fetch and parse JSON.

    import requests
    response = requests.get("https://jsonplaceholder.typicode.com/users")
    users = response.json()
    print(users[0]["name"])
  2. Configuration files – Many apps use .json files to store settings.

  3. Data analysis – JSON is common in datasets (e.g., logs, sensor data).

  4. Database communication – NoSQL databases like MongoDB rely heavily on JSON-like documents.

What if You Don’t Have Python Installed?

If you just want to open a JSON file and explore its contents without programming:

  • Use online tools like: https://onlinejsonformatter.com

  • Many modern code editors (VS Code, Sublime, Atom) provide JSON syntax highlighting.

Best Practices When Working with JSON in Python

  • Always validate your JSON using online tools before parsing.

  • Use with open() for safe file handling (it auto-closes the file).

  • Use try-except blocks to handle parsing errors.

  • Prefer json.load() for files and json.loads() for strings.

  • Use indent and sort_keys when saving JSON for readability.

Conclusion

Reading and working with JSON in Python is straightforward thanks to the built-in json module. Whether you’re fetching data from APIs, configuring applications, or analyzing datasets, JSON is a format you’ll deal with regularly.

To recap, you’ve learned:

  • What JSON is and why it’s widely used.

  • How Python naturally maps JSON to dictionaries and lists.

  • Different methods (json.load, json.loads) to read JSON.

  • How to write JSON back to files with json.dump.

  • Error handling and real-world use cases.

If you don’t have Python installed, you can still view JSON files online. Just visit online JSON Formatter, upload your file, and it will open in an easy-to-use JSON editor.

Lucky Me I See Ghosts Hoodie A Cultural Phenomenon

Introduction: The Hoodie That Changed the Game Streetwear thrives on exclusivity, creativity, and cultural influence. Few pieces embody this better than the Lucky Me I...

Getting Started with STM32 HAL Library in CubeIDE

Many beginners start STM32 projects but get confused between HAL, LL, and direct register programming. Without knowing where to begin, the process feels overwhelming....

The Benefits of Australian-Made Timber Furniture

Are you amazed by the elegance of natural timber and wish to incorporate it into your home decor? Are you a firm believer in...

Wall Dimension 3D Wall Panels for Modern Interiors

When it comes to enhancing the aesthetics and acoustics of modern interiors, Wall Dimension 3D Wall Panels are among the most innovative and stylish...

Who Offers The Best of Performance Appraisal Software in SG

Performance management holds a central place in modern workplaces. Companies that assess, guide, and uplift their people grow stronger from within. In Singapore, HR...

Muskoka Cottage Rentals: Everything You Need to Know

Few destinations capture the essence of Canadian cottage life quite like Muskoka. With its sparkling lakes, towering pines, and charming small towns, it’s no...
Skip to toolbar