Handling None Json issue - hemanth22/fastapi-webhook-receiver GitHub Wiki
Handling None Json issue
import json
import re
# Function to correct the formatting issues
def correct_json_format(input_str):
# Remove extra spaces after colons in timestamps and URLs
corrected_str = re.sub(r'(\d+):\s(\d+)', r'\1:\2', input_str)
corrected_str = re.sub(r'https: //', r'https://', corrected_str)
return corrected_str
# Function to read, correct, and write JSON data
def process_json(input_file, output_file):
try:
# Read the input file
with open(input_file, 'r') as file:
input_str = file.read()
# Correct the JSON format
corrected_str = correct_json_format(input_str)
# Convert single quotes to double quotes for valid JSON
corrected_str = corrected_str.replace("'", '"')
# Replace Python None with JSON null
corrected_str = corrected_str.replace("None", "null")
corrected_str = corrected_str.replace("False", "false")
# Load the corrected string as JSON
json_data = json.loads(corrected_str)
# Write the corrected JSON to the output file
with open(output_file, 'w') as file:
json.dump(json_data, file, indent=4)
print(f"Corrected JSON data has been written to {output_file}")
except FileNotFoundError:
print(f"File {input_file} not found.")
except json.JSONDecodeError as e:
print(f"Error decoding JSON: {e}")
except Exception as e:
print(f"An error occurred: {e}")
# Input and output file paths
input_file = 'data.json'
output_file = 'new_data.json'
# Process the JSON data
process_json(input_file, output_file)
data.json
{'source': 'GitGuardian', 'timestamp': '2024-08-05T16: 46: 20.255960Z', 'action': 'incident_reopened', 'message': 'This incident has been reopened.', 'target_user': 'Hemanth B <[email protected]>', 'incident': {'id': 5505127, 'date': '2023-01-16T14: 40: 06.079644Z', 'detector': None, 'secret_hash': None, 'hmsl_hash': None, 'secret_revoked': None, 'validity': None, 'occurrence_count': 3, 'status': 'triggered', 'regression': False, 'assignee_email': None, 'severity': 'info', 'ignored_at': None, 'ignore_reason': None, 'resolved_at': None, 'gitguardian_url': 'https: //dashboard.gitguardian.com/workspace/6741/incidents/5505127', 'share_url': None}}
json_reformater.py