import json
import re
def fix_json(json_string):
"""
Attempts to fix common JSON errors in a string.
Includes defensive checks to avoid crashing on invalid input.
"""
try:
# Attempt to load the JSON string
data = json.loads(json_string)
return data # Return if valid JSON
except json.JSONDecodeError as e:
print(f"Initial JSON decode error: {e}")
# Attempt to fix common errors: missing commas, trailing commas
fixed_string = json_string.replace('}{', '},{') #Fixes trailing commas
fixed_string = re.sub(r',}', ')', fixed_string) #Fixes missing commas
try:
data = json.loads(fixed_string)
return data # Return if fixed JSON
except json.JSONDecodeError as e2:
print(f"Fixing JSON decode error: {e2}")
return None # Return None if fixing fails
if __name__ == '__main__':
#Example Usage
#Valid JSON
valid_json = '{"name": "John", "age": 30}'
fixed_data = fix_json(valid_json)
if fixed_data:
print(f"Valid JSON fixed: {fixed_data}")
#JSON with trailing comma
trailing_comma_json = '{"name": "John", "age": 30,}'
fixed_data = fix_json(trailing_comma_json)
if fixed_data:
print(f"Trailing comma JSON fixed: {fixed_data}")
#JSON with missing comma
missing_comma_json = '{"name": "John" "age": 30}'
fixed_data = fix_json(missing_comma_json)
if fixed_data:
print(f"Missing comma JSON fixed: {fixed_data}")
#Invalid JSON
invalid_json = '{"name": "John", "age": 30'
fixed_data = fix_json(invalid_json)
if fixed_data is None:
print("Invalid JSON not fixed.")
Add your comment