| import csv |
| import pandas as pd |
|
|
| class CSVtoJSONTransformer: |
| def __init__(self, csv_reader): |
| self.csv_reader = csv_reader |
| |
| def transform_to_json(self): |
| df = pd.DataFrame(self.csv_reader) |
| df["Author"] = df["Author"].replace({pd.NA: None}) |
| df["Comment Body"] = df["Comment Body"].replace({pd.NA: None}) |
|
|
| |
| transformed_data = [] |
|
|
| |
| grouped_df = df.groupby('Subreddit') |
|
|
| |
| for subreddit, group in grouped_df: |
| subreddit_data = { |
| "Subreddit": subreddit, |
| "Posts": [] |
| } |
| |
| |
| for index, row in group.iterrows(): |
| post_title = row['Post Title'] |
| comment_body = row['Comment Body'] |
| timestamp = row['Timestamp'] |
| upvotes = row['Upvotes'] |
| ID = row['ID'] |
| author = row['Author'] |
| replies = row['Number of Replies'] |
| |
| |
| post_exists = False |
| for post in subreddit_data["Posts"]: |
| if post['PostTitle'] == post_title: |
| post_exists = True |
| post['Comments'].append({ |
| "CommentID": ID, |
| "Author": author, |
| "CommentBody": comment_body, |
| "Timestamp": timestamp, |
| "Upvotes": upvotes, |
| "NumberofReplies": replies |
| }) |
| break |
| |
| |
| if not post_exists: |
| subreddit_data["Posts"].append({ |
| "PostID": len(subreddit_data["Posts"]) + 1, |
| "PostTitle": post_title, |
| "Comments": [{ |
| "CommentID": ID, |
| "Author": author, |
| "CommentBody": comment_body, |
| "Timestamp": timestamp, |
| "Upvotes": upvotes, |
| "NumberofReplies": replies |
| }] |
| }) |
| |
| |
| transformed_data.append(subreddit_data) |
|
|
| return transformed_data |