Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import json
- import csv
- def extract_paid_messages(json_data):
- messages = []
- # Check if 'replayChatItemAction' and 'actions' keys exist
- if 'replayChatItemAction' in json_data and 'actions' in json_data['replayChatItemAction']:
- for action in json_data['replayChatItemAction']['actions']:
- # Check if the required keys exist in the structure
- if 'addChatItemAction' in action and 'item' in action['addChatItemAction']:
- item = action['addChatItemAction']['item']
- if 'liveChatPaidMessageRenderer' in item:
- renderer = item['liveChatPaidMessageRenderer']
- # Extracting the desired details
- name = renderer['authorName']['simpleText']
- message = None
- if ('message' in renderer and
- 'runs' in renderer['message'] and
- renderer['message']['runs'] and
- 'text' in renderer['message']['runs'][0]):
- message = renderer['message']['runs'][0]['text']
- amount = renderer['purchaseAmountText']['simpleText']
- messages.append({
- 'name': name,
- 'message': message,
- 'amount': amount
- })
- return messages
- # List to accumulate all results
- all_results = []
- # Read from a file
- with open('#11.json', 'r', encoding='utf-8') as file:
- for line in file:
- data = json.loads(line)
- results = extract_paid_messages(data)
- all_results.extend(results) # Add the results to the accumulated list
- # Now, write the accumulated results to the CSV file
- with open('output.csv', 'w', newline='', encoding='utf-8') as csvfile:
- fieldnames = ['name', 'message', 'amount']
- writer = csv.DictWriter(csvfile, fieldnames=fieldnames, delimiter='|')
- writer.writeheader()
- for msg in all_results:
- writer.writerow(msg)
Advertisement
Add Comment
Please, Sign In to add comment