Learn to read a JSON file in Python with the help of json.load() method which reads the data into a Python object.
For quick reference, below is the code which reads a JSON file to a Python object.
import json with open('file_dir_location/data.json') as fp: data = json.load(fp) # The data is of type 'dict' print(data)
1. json.load() Method
The json.load()
deserializes a given JSON file from the filesystem and converts to a python dictionary object using these conversion rules.
JSON | Python |
---|---|
object |
|
array |
|
string |
|
number (int) |
|
number (real) |
float |
true |
True |
false |
False |
null |
None |
2. Python Read JSON File Examples
Example 1: Reading a JSON file from Filesystem
[ { "id": 1, "name": "Lokesh", "username": "lokesh", "email": "lokesh@gmail.com" }, { "id": 2, "name": "Brian", "username": "brian", "email": "brian@gmail.com" } ]
The users.json
contains an array, so when we read the file – we get Python list object.
import json with open('users.json') as fp: data = json.load(fp) # list print(type(data)) # Verify read data print(data)
Program output.
<class 'list'> [{'id': 1, 'name': 'Lokesh', 'username': 'lokesh', 'email': 'lokesh@gmail.com'}, {'id': 2, 'name': 'Brian', 'username': 'brian', 'email': 'brian@gmail.com'}]
Example 2: Reading a JSON file from URL
We will use the Python Requests library which is a simple, yet elegant HTTP library.
import json import requests response = requests.get("https://jsonplaceholder.typicode.com/users") users = json.loads(response.text) print(users)
Program output has not been printed in this tutorial. Please run the program to see the complete output.
[{'id': 1, 'name': 'Leanne Graham', 'username': 'Bret', 'email': 'Sincere@april.biz'} ... ]
Happy Learning !!
Leave a Reply