How to read JSON in Python
Posted in Python by Dirk - last update: Feb 14, 2024
To load a JSON file in Python, you can use the json
module, which is part of the standard library. The json
module in Python provides two main functions for loading JSON data: json.load()
for loading JSON data from a file-like object and json.loads()
for loading JSON data from a JSON-formatted string.
Both functions parse the JSON data and return a native Python object (typically a dictionary, list, string, number, boolean, or None).
What is JSON
JSON, or JavaScript Object Notation, is a lightweight data interchange format that is easy for humans to read and write and easy for machines to parse and generate.
It is a text format that is completely language-independent but uses conventions that are familiar to programmers of the C family of languages (C, C++, C#, Java, JavaScript, and others).
JSON is often used to transmit data between a server and a web application, as well as for configuration files and data storage.
{
"employees": [
{
"id": 1,
"name": "Alice",
"position": "Software Engineer",
"salary": 75000
},
{
"id": 2,
"name": "Bob",
"position": "Data Scientist",
"salary": 80000
}
],
"department": "Technology",
"company": "ABC Tech"
}
In this example, we have a JSON object containing information about employees in a company.
There are two employee data points within the “employees” array, each with “id,” “name,” “position,” and “salary” fields.
The JSON object also includes “department” and “company” fields at the top level.
How to read JSON from a file
To read JSON from a file you use the json.load()
function
Syntax: json.load(file, *, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)
This function is used to load JSON data from a file-like object (e.g., a file handle opened with open()
or an io.StringIO
object).
Parameters:
file
: A file-like object (e.g., an open file handle).
object_hook
, parse_float
, parse_int
, parse_constant
, object_pairs_hook
: Optional parameters for customizing the decoding process.
Example:
import json
# Specify the path to your JSON file
file_path = 'example.json'
# Open the file and load its content
with open(file_path, 'r') as file:
data_from_file = json.load(file)
# Now, data_from_file contains the parsed JSON data
print(data_from_file)
How to read JSON from a string
To read JSON from a file you use the json.loads()
function
Syntax: json.loads(s, *, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)
This function is used to load JSON data from a JSON-formatted string.
Parameters:
s
: A string containing JSON-formatted data.
object_hook
, parse_float
, parse_int
, parse_constant
, object_pairs_hook
: Optional parameters for customizing the decoding process.
Example:
import json
# JSON string example
json_string = '{"employees": [{"id": 1,"name": "Alice","position": "Software Engineer","salary": 75000},{"id": 2,"name": "Bob","position": "Data Scientist","salary": 80000}],"department": "Technology", "company": "ABC Tech"}'
# Parse the JSON string
data_from_string = json.loads(json_string)
# Now, data_from_string contains the parsed JSON data
print('JSON data:', data_from_string)
# It is converted to a native python object
print('Data type:',type(data_from_string))
Output:
JSON data: {'employees': [{'id': 1, 'name': 'Alice', 'position': 'Software Engineer', 'salary': 75000}, {'id': 2, 'name': 'Bob', 'position': 'Data Scientist', 'salary': 80000}], 'department': 'Technology', 'company': 'ABC Tech'}
Data type: <class 'dict'>
After running this code, data_from_string
will be a Python dictionary with the same structure as the JSON. You can then access the data using Python syntax. For example:
# Accessing data from the converted Python dictionary
employees = data_from_string['employees']
for employee in employees:
print(f"ID: {employee['id']}, Name: {employee['name']}, Position: {employee['position']}, Salary: {employee['salary']}")
department = data_from_string['department']
company = data_from_string['company']
print(f"Department: {department}, Company: {company}")
This will give the following output
ID: 1, Name: Alice, Position: Software Engineer, Salary: 75000
ID: 2, Name: Bob, Position: Data Scientist, Salary: 80000
Department: Technology, Company: ABC Tech
Now you have the JSON data in a native Python format, and you can work with it as you would with any Python data structure.
Conversion table;
Here’s a table outlining the corresponding Python objects for various JSON data types:
JSON Data Type |
JSON Example |
Python Equivalent |
Object |
{“key”: “value”, “number”: 42} |
Dictionary (dict) |
Array |
[“apple”, “orange”, “banana”] |
List (list) |
String |
“Hello, World!” |
String (str) |
Number |
42 or 3.14 |
Integer (int) or Float (float) |
Boolean |
true or false |
Boolean (bool) |
Null |
null |
None (NoneType) |
|
|
|
When using the json
module in Python, it automatically converts these JSON data types to their corresponding native Python equivalents.
Other articles