-
Notifications
You must be signed in to change notification settings - Fork 9
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
f75b560
commit 748cd29
Showing
1 changed file
with
39 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
import boto3 | ||
import json | ||
|
||
# Initialize S3 client | ||
s3_client = boto3.client('s3') | ||
|
||
def count_key_value_pairs(json_data): | ||
try: | ||
data = json.loads(json_data) | ||
if isinstance(data, dict): | ||
return len(data) # Return the number of key-value pairs | ||
else: | ||
return 0 | ||
except json.JSONDecodeError: | ||
return 0 | ||
|
||
def process_s3_files(bucket_name, prefix): | ||
# List objects in the bucket with the given prefix | ||
response = s3_client.list_objects_v2(Bucket=bucket_name, Prefix=prefix) | ||
|
||
if 'Contents' not in response: | ||
print(f"No files found with prefix '{prefix}' in bucket '{bucket_name}'.") | ||
return | ||
|
||
for obj in response['Contents']: | ||
file_key = obj['Key'] | ||
|
||
# Download file content | ||
file_obj = s3_client.get_object(Bucket=bucket_name, Key=file_key) | ||
file_content = file_obj['Body'].read().decode('utf-8') | ||
|
||
# Count the key-value pairs in the JSON file | ||
num_pairs = count_key_value_pairs(file_content) | ||
print(f"File: {file_key}, Key-Value Pairs: {num_pairs}") | ||
|
||
# Example usage | ||
bucket_name = 'datastream-resources' | ||
prefix = 'weights' | ||
process_s3_files(bucket_name, prefix) |