
- Python - Home
- Python - Overview
- Python - History
- Python - Features
- Python vs C++
- Python - Hello World Program
- Python - Application Areas
- Python - Interpreter
- Python - Environment Setup
- Python - Virtual Environment
- Python - Basic Syntax
- Python - Variables
- Python - Data Types
- Python - Type Casting
- Python - Unicode System
- Python - Literals
- Python - Operators
- Python - Arithmetic Operators
- Python - Comparison Operators
- Python - Assignment Operators
- Python - Logical Operators
- Python - Bitwise Operators
- Python - Membership Operators
- Python - Identity Operators
- Python - Operator Precedence
- Python - Comments
- Python - User Input
- Python - Numbers
- Python - Booleans
- Python - Control Flow
- Python - Decision Making
- Python - If Statement
- Python - If else
- Python - Nested If
- Python - Match-Case Statement
- Python - Loops
- Python - for Loops
- Python - for-else Loops
- Python - While Loops
- Python - break Statement
- Python - continue Statement
- Python - pass Statement
- Python - Nested Loops
- Python Functions & Modules
- Python - Functions
- Python - Default Arguments
- Python - Keyword Arguments
- Python - Keyword-Only Arguments
- Python - Positional Arguments
- Python - Positional-Only Arguments
- Python - Arbitrary Arguments
- Python - Variables Scope
- Python - Function Annotations
- Python - Modules
- Python - Built in Functions
- Python Strings
- Python - Strings
- Python - Slicing Strings
- Python - Modify Strings
- Python - String Concatenation
- Python - String Formatting
- Python - Escape Characters
- Python - String Methods
- Python - String Exercises
- Python Lists
- Python - Lists
- Python - Access List Items
- Python - Change List Items
- Python - Add List Items
- Python - Remove List Items
- Python - Loop Lists
- Python - List Comprehension
- Python - Sort Lists
- Python - Copy Lists
- Python - Join Lists
- Python - List Methods
- Python - List Exercises
- Python Tuples
- Python - Tuples
- Python - Access Tuple Items
- Python - Update Tuples
- Python - Unpack Tuples
- Python - Loop Tuples
- Python - Join Tuples
- Python - Tuple Methods
- Python - Tuple Exercises
- Python Sets
- Python - Sets
- Python - Access Set Items
- Python - Add Set Items
- Python - Remove Set Items
- Python - Loop Sets
- Python - Join Sets
- Python - Copy Sets
- Python - Set Operators
- Python - Set Methods
- Python - Set Exercises
- Python Dictionaries
- Python - Dictionaries
- Python - Access Dictionary Items
- Python - Change Dictionary Items
- Python - Add Dictionary Items
- Python - Remove Dictionary Items
- Python - Dictionary View Objects
- Python - Loop Dictionaries
- Python - Copy Dictionaries
- Python - Nested Dictionaries
- Python - Dictionary Methods
- Python - Dictionary Exercises
- Python Arrays
- Python - Arrays
- Python - Access Array Items
- Python - Add Array Items
- Python - Remove Array Items
- Python - Loop Arrays
- Python - Copy Arrays
- Python - Reverse Arrays
- Python - Sort Arrays
- Python - Join Arrays
- Python - Array Methods
- Python - Array Exercises
- Python File Handling
- Python - File Handling
- Python - Write to File
- Python - Read Files
- Python - Renaming and Deleting Files
- Python - Directories
- Python - File Methods
- Python - OS File/Directory Methods
- Python - OS Path Methods
- Object Oriented Programming
- Python - OOPs Concepts
- Python - Classes & Objects
- Python - Class Attributes
- Python - Class Methods
- Python - Static Methods
- Python - Constructors
- Python - Access Modifiers
- Python - Inheritance
- Python - Polymorphism
- Python - Method Overriding
- Python - Method Overloading
- Python - Dynamic Binding
- Python - Dynamic Typing
- Python - Abstraction
- Python - Encapsulation
- Python - Interfaces
- Python - Packages
- Python - Inner Classes
- Python - Anonymous Class and Objects
- Python - Singleton Class
- Python - Wrapper Classes
- Python - Enums
- Python - Reflection
- Python Errors & Exceptions
- Python - Syntax Errors
- Python - Exceptions
- Python - try-except Block
- Python - try-finally Block
- Python - Raising Exceptions
- Python - Exception Chaining
- Python - Nested try Block
- Python - User-defined Exception
- Python - Logging
- Python - Assertions
- Python - Built-in Exceptions
- Python Multithreading
- Python - Multithreading
- Python - Thread Life Cycle
- Python - Creating a Thread
- Python - Starting a Thread
- Python - Joining Threads
- Python - Naming Thread
- Python - Thread Scheduling
- Python - Thread Pools
- Python - Main Thread
- Python - Thread Priority
- Python - Daemon Threads
- Python - Synchronizing Threads
- Python Synchronization
- Python - Inter-thread Communication
- Python - Thread Deadlock
- Python - Interrupting a Thread
- Python Networking
- Python - Networking
- Python - Socket Programming
- Python - URL Processing
- Python - Generics
- Python Libraries
- NumPy Tutorial
- Pandas Tutorial
- SciPy Tutorial
- Matplotlib Tutorial
- Django Tutorial
- OpenCV Tutorial
- Python Miscellenous
- Python - Date & Time
- Python - Maths
- Python - Iterators
- Python - Generators
- Python - Closures
- Python - Decorators
- Python - Recursion
- Python - Reg Expressions
- Python - PIP
- Python - Database Access
- Python - Weak References
- Python - Serialization
- Python - Templating
- Python - Output Formatting
- Python - Performance Measurement
- Python - Data Compression
- Python - CGI Programming
- Python - XML Processing
- Python - GUI Programming
- Python - Command-Line Arguments
- Python - Docstrings
- Python - JSON
- Python - Sending Email
- Python - Further Extensions
- Python - Tools/Utilities
- Python - GUIs
- Python Advanced Concepts
- Python - Abstract Base Classes
- Python - Custom Exceptions
- Python - Higher Order Functions
- Python - Object Internals
- Python - Memory Management
- Python - Metaclasses
- Python - Metaprogramming with Metaclasses
- Python - Mocking and Stubbing
- Python - Monkey Patching
- Python - Signal Handling
- Python - Type Hints
- Python - Automation Tutorial
- Python - Humanize Package
- Python - Context Managers
- Python - Coroutines
- Python - Descriptors
- Python - Diagnosing and Fixing Memory Leaks
- Python - Immutable Data Structures
- Python Useful Resources
- Python - Questions & Answers
- Python - Interview Questions & Answers
- Python - Online Quiz
- Python - Quick Guide
- Python - Reference
- Python - Cheatsheet
- Python - Projects
- Python - Useful Resources
- Python - Discussion
- Python Compiler
- NumPy Compiler
- Matplotlib Compiler
- SciPy Compiler
Python json.load() Function
The Python json.load() function is used to read JSON data from a file and convert it into a corresponding Python object.
This function is useful when dealing with data stored in JSON format, such as configuration files, API responses, or structured data storage.
Syntax
Following is the syntax of the Python json.load() function −
json.load(fp, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None)
Parameters
This function accepts the following parameters −
- fp: A file-like object from which JSON data will be read.
-
cls (optional): A custom decoder class that subclasses
json.JSONDecoder
. - object_hook (optional): A function that transforms dictionary objects.
-
parse_float (optional): A function that parses floating-point numbers. Default is
float
. -
parse_int (optional): A function that parses integer numbers. Default is
int
. - parse_constant (optional): A function that parses constant values such as NaN and Infinity.
- object_pairs_hook (optional): A function that processes key-value pairs in a dictionary.
Return Value
This function returns a Python object that represents the JSON data from the file.
Example: Basic Usage
In this example, we use the json.load() function to read JSON data from a file (data.json) and convert it into a Python dictionary −
JSON File (data.json):
Below is the content of our "data.json" file −
{ "name": "John", "age": 30, "city": "New York" }
Following is our code −
import json # Open the JSON file for reading with open('data.json', 'r') as file: # Deserialize JSON data into a Python dictionary data = json.load(file) print("Data from file:", data)
Following is the data read in the file −
Data from file: {'name': 'John', 'age': 30, 'city': 'New York'}
Example: Custom Parsing
The object_hook parameter allows us to define a custom function that modifies the JSON objects when they are loaded. In this example, we convert all keys to uppercase. −
import json # Custom function to transform JSON objects def custom_decoder(obj): return {key.upper(): value for key, value in obj.items()} # Open the JSON file for reading with open('data.json', 'r') as file: # Deserialize JSON data with custom object_hook data = json.load(file, object_hook=custom_decoder) print("Transformed Data:", data)
We obtain the following converted custom Python objects in our file −
Transformed Data: {'NAME': 'John', 'AGE': 30, 'CITY': 'New York'}
Example: Parsing Numbers
In this example, we use the parse_int and parse_float parameters to customize how numbers are processed while loading JSON data −
JSON File (numbers.json):
Below is the content of our "numbers.json" file −
{ "integer": "10", "floating": "12.3456" }
Following is our code −
import json # Custom parsing functions def parse_int_custom(value): return int(value) * 10 # Multiply integers by 10 def parse_float_custom(value): return round(float(value), 2) # Round floats to 2 decimal places # Open the JSON file for reading with open('numbers.json', 'r') as file: # Deserialize JSON data with custom number parsing data = json.load(file, parse_int=parse_int_custom, parse_float=parse_float_custom) print("Parsed Data:", data)
Following customization is reflect in our file −
Parsed Data: {'integer': '10', 'floating': '12.3456'}
Example: Preserving Key Order
By default, dictionaries in Python do not maintain order before Python 3.7. If you need to preserve the order of keys while reading JSON, you can use the object_pairs_hook parameter with OrderedDict −
import json from collections import OrderedDict # Open the JSON file for reading with open('data.json', 'r') as file: # Deserialize JSON data while preserving key order data = json.load(file, object_pairs_hook=OrderedDict) print("Ordered Data:", data)
Following details is obtained in our file −
Ordered Data: OrderedDict({'name': 'John', 'age': 30, 'city': 'New York'})