boto3
Python
JSON
S3
file-handling

Read a JSON file from S3 with Python boto3

Codemia Knowledge Hub ·

To read a JSON file from S3 with boto3, call get_object on an S3 client, read and decode the response body, and pass the string to json.loads:

data = json.loads(s3_client.get_object(Bucket=bucket, Key=key)['Body'].read().decode('utf-8'))

The rest of this page covers setup, a full example and error handling.

Prerequisites

  • AWS account.
  • IAM user with the necessary permissions (AmazonS3ReadOnlyAccess).
  • AWS credentials: your AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY.
  • Python (preferably 3.7 or higher) with boto3 installed:
bash
pip install boto3

Configuring credentials

  1. Configuration: set your AWS credentials and region with environment variables or the AWS CLI:
bash
   aws configure

Or set them in code:

python
1   import boto3
2
3   session = boto3.Session(
4       aws_access_key_id='YOUR_ACCESS_KEY',
5       aws_secret_access_key='YOUR_SECRET_KEY',
6       region_name='us-west-2'
7   )
  1. IAM roles (optional): when the script runs on an AWS service such as EC2, use an IAM role for access instead.

Avoid hardcoding credentials in real applications; use environment variables or IAM roles.

Reading and parsing the JSON file

python
1import boto3
2import json
3
4# Initialize a session using your credentials
5session = boto3.Session(
6    aws_access_key_id='YOUR_ACCESS_KEY',
7    aws_secret_access_key='YOUR_SECRET_KEY',
8    region_name='us-west-2'
9)
10
11# Initialize the S3 client
12s3_client = session.client('s3')
13
14# Specify the bucket name and the object key
15bucket_name = 'your-bucket-name'
16object_key = 'path/to/your/jsonfile.json'
17
18# Fetch the object from S3
19response = s3_client.get_object(Bucket=bucket_name, Key=object_key)
20
21# Read the content of the file
22content = response['Body'].read().decode('utf-8')
23
24# Parse the JSON data
25data = json.loads(content)
26
27# Use the data
28print(data)
  • Session and client: a session is created with your credentials, and the S3 client comes from that session.
  • Fetching: get_object retrieves the file.
  • Decoding: S3 returns a binary stream, so the body must be read and decoded to a string.
  • Parsing: json.loads() converts the string into a Python dictionary.

Handling missing keys and buckets

Catch the specific S3 exceptions plus a general fallback:

python
1try:
2    response = s3_client.get_object(Bucket=bucket_name, Key=object_key)
3    content = response['Body'].read().decode('utf-8')
4    data = json.loads(content)
5except s3_client.exceptions.NoSuchKey:
6    print("The specified key does not exist.")
7except s3_client.exceptions.NoSuchBucket:
8    print("The specified bucket does not exist.")
9except Exception as e:
10    print("An error occurred: ", e)
FeatureDescription
AuthenticationUse IAM roles or AWS credentials (ACCESS_KEY and SECRET_KEY).
ConfigurationSet AWS region and credentials via environment or code.
Object RetrievalUtilize s3_client.get_object to access files from an S3 bucket.
Data ParsingDecode and utilize json.loads() for parsing JSON.
Error ManagementImplement exception handling for robust code.

Other options

  • boto3.resource provides a higher-level abstraction if you interact with S3 more extensively.
  • AWS Lambda with S3 triggers can process JSON files in real time as they arrive in your bucket.

Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design