Apply Now Apply Now Apply Now
header_logo
Post thumbnail
PYTHON

How to Read JSON File in Python: A Complete Guide

By Vishalini Devarajan

Many Python developers working with APIs, configuration files, and data pipelines encounter JSON as the most common data exchange format. Knowing how to read JSON file in Python correctly, access nested values, handle errors, and work with large files is a foundational skill for backend development, data engineering, and automation. This guide walks through every practical scenario you will encounter when working with JSON in Python.

Table of contents


  1. TL;DR Summary
  2. What Is JSON and Why Is It Used?
  3. JSON to Python Type Mapping
  4. How to Read a JSON File in Python
    • Method 1: Using json.load() to Read from a File
    • Method 2: Using json.loads() to Parse a JSON String
  5. How to Access JSON Data in Python
  6. Reading a JSON File with Multiple Records
  7. Conclusion
  8. FAQ
    • How do I read a JSON file in Python? 
    • What is the difference between json.load() and json.loads()? 
    • How do I access nested values in a JSON file in Python? 
    • How do I read JSON data from an API in Python? 
    • What happens if the JSON file has invalid formatting? 
    • How do I read a large JSON file in Python without running out of memory? 
    • How do I handle missing keys when reading JSON in Python? 
    • Why should I specify encoding when opening a JSON file in Python? 

TL;DR Summary

  • Reading a JSON file in Python is done using the built-in json module with the json.load() function to read from a file or json.loads() to parse a JSON string.
  • Python converts JSON data automatically into native Python objects: objects become dictionaries, arrays become lists, strings remain strings, and numbers remain integers or floats.
  • This guide covers every method to read, access, and handle JSON files in Python with practical code examples.

Want to build strong Python data handling skills with real-world projects and structured guidance? Explore HCL GUVI’s Python Programming Course, designed for beginners and professionals who want to apply Python confidently in production.

What Is JSON and Why Is It Used?

JSON (JavaScript Object Notation) is a lightweight, human-readable format for storing and exchanging structured data. It is the standard format used by REST APIs, configuration files, and databases like MongoDB.

A JSON file looks like this:

{

    "name": "Priya",

    "age": 28,

    "skills": ["Python", "SQL", "AWS"],

    "address": {

        "city": "Chennai",

        "state": "Tamil Nadu"

    }

}

JSON supports six data types: strings, numbers, booleans, null, arrays, and objects. Python maps each of these directly to native types when loading.

Read More: File Handling in Python: A Beginner’s Simple Guide

JSON to Python Type Mapping

When you load a JSON file in Python, the json module converts each JSON type automatically:

JSON TypePython Type
objectdict
arraylist
stringstr
number (int)int
number (float)float
true / falseTrue / False
nullNone

Understanding this mapping helps you access and manipulate JSON data correctly after loading it.

💡 Did You Know?

Python’s built-in json module includes a C accelerator called _json that is automatically used when available. This optimized implementation can dramatically speed up JSON parsing and serialization compared to the pure Python fallback, especially for large files and high-volume data processing. As a result, Python’s standard json module delivers excellent real-world performance without requiring developers to install additional JSON libraries in most applications.

How to Read a JSON File in Python

Method 1: Using json.load() to Read from a File

json.load() reads directly from a file object. This is the standard method for reading JSON from a file on disk.

import json

with open("data.json", "r", encoding="utf-8") as file:

    data = json.load(file)

print(data)

print(type(data))  # Output: <class 'dict'>

Always use encoding=”utf-8″ to handle special characters correctly. The with statement ensures the file closes automatically after reading.

MDN

Method 2: Using json.loads() to Parse a JSON String

json.loads() parses a JSON-formatted string rather than a file. This is the method to use when you receive JSON data from an API response or a variable.

import json

json_string = '{"name": "Arun", "age": 25, "city": "Bangalore"}'

data = json.loads(json_string)

print(data["name"])   # Output: Arun

print(data["age"])    # Output: 25

Note the difference: json.load() takes a file object. json.loads() takes a string. The s in loads stands for string.

Want to build strong Python data handling skills with real-world projects and structured guidance? Explore HCL GUVI’s Python Programming Course, designed for beginners and professionals who want to apply Python confidently in production.

How to Access JSON Data in Python

Once loaded, JSON data becomes a standard Python dictionary. Access values using keys and indices.

import json

with open("employee.json", "r") as file:

    employee = json.load(file)

# Access top-level keys

print(employee["name"])           # Output: Priya

print(employee["age"])            # Output: 28

# Access a list value

print(employee["skills"][0])      # Output: Python

# Access nested object

print(employee["address"]["city"])  # Output: Chennai

Use square bracket notation for direct access. Use the .get() method to safely access keys that may not exist:

city = employee.get("address", {}).get("city", "Unknown")

print(city)  # Output: Chennai

.get() returns None by default instead of raising a KeyError when the key is missing.

Reading a JSON File with Multiple Records

JSON files often contain a list of objects rather than a single object. Iterate over the list after loading.

Sample JSON file (employees.json):

[

    {"name": "Arun", "department": "Engineering"},

    {"name": "Priya", "department": "Data Science"},

    {"name": "Rahul", "department": "DevOps"}

]

Reading and iterating:

import json

with open("employees.json", "r") as file:

    employees = json.load(file)

for employee in employees:

    print(f"{employee['name']} - {employee['department']}")

# Output:

# Arun - Engineering

# Priya - Data Science

# Rahul - DevOps

The json.load() call returns a Python list here because the top-level JSON structure is an array.

💡 Did You Know?

JSON (JavaScript Object Notation) was popularized by Douglas Crockford in the early 2000s as a lightweight alternative to XML for exchanging data between applications. Today, JSON is supported natively by virtually every major programming language and has become the de facto standard format for REST APIs and web services. Python has included the built-in json module since Python 2.6, making it easy to parse, generate, and manipulate JSON data without installing any additional libraries.

Conclusion

Reading JSON files in Python is a foundational skill that appears in almost every real-world Python project, from loading API responses and configuration files to processing large data pipelines. The json module covers the majority of use cases cleanly with just two functions: json.load() for files and json.loads() for strings.

As your projects grow, remember to handle encoding correctly, use .get() for safe key access, validate API responses before parsing, and switch to ijson for large files..

FAQ

How do I read a JSON file in Python? 

Use the json module with json.load() to read from a file object opened in read mode, or json.loads() to parse a JSON-formatted string.

What is the difference between json.load() and json.loads()? 

json.load() reads from a file object. json.loads() parses a JSON string. The s in loads stands for string.

How do I access nested values in a JSON file in Python? 

Chain dictionary keys and list indices: data[“address”][“city”] accesses a nested key. Use .get() to safely access keys that may not exist without raising a KeyError.

How do I read JSON data from an API in Python? 

Use the requests library and call response.json() on a successful response. This internally parses the JSON response body and returns a Python dictionary or list.

What happens if the JSON file has invalid formatting? 

Python raises a json.JSONDecodeError. Always wrap json.load() calls in a try-except block to handle malformed files gracefully in production code.

How do I read a large JSON file in Python without running out of memory? 

Use the ijson library, which parses JSON files incrementally one record at a time without loading the entire file into memory.

How do I handle missing keys when reading JSON in Python? 

Use the .get() method with a default value: data.get(“key”, “default”). This returns the default instead of raising a KeyError when the key is absent.

MDN

Why should I specify encoding when opening a JSON file in Python? 

JSON files containing non-ASCII characters fail to read correctly without explicit encoding. Always use encoding=”utf-8″ when opening any text file in Python to handle international characters correctly.

Success Stories

Did you enjoy this article?

Schedule 1:1 free counselling

Similar Articles

Loading...
Get in Touch
Chat on Whatsapp
Request Callback
Share logo Copy link
Table of contents Table of contents
Table of contents Articles
Close button

  1. TL;DR Summary
  2. What Is JSON and Why Is It Used?
  3. JSON to Python Type Mapping
  4. How to Read a JSON File in Python
    • Method 1: Using json.load() to Read from a File
    • Method 2: Using json.loads() to Parse a JSON String
  5. How to Access JSON Data in Python
  6. Reading a JSON File with Multiple Records
  7. Conclusion
  8. FAQ
    • How do I read a JSON file in Python? 
    • What is the difference between json.load() and json.loads()? 
    • How do I access nested values in a JSON file in Python? 
    • How do I read JSON data from an API in Python? 
    • What happens if the JSON file has invalid formatting? 
    • How do I read a large JSON file in Python without running out of memory? 
    • How do I handle missing keys when reading JSON in Python? 
    • Why should I specify encoding when opening a JSON file in Python?