1. import json
  2. import re
  3. def fix_json(json_string):
  4. """
  5. Attempts to fix common JSON errors in a string.
  6. Includes defensive checks to avoid crashing on invalid input.
  7. """
  8. try:
  9. # Attempt to load the JSON string
  10. data = json.loads(json_string)
  11. return data # Return if valid JSON
  12. except json.JSONDecodeError as e:
  13. print(f"Initial JSON decode error: {e}")
  14. # Attempt to fix common errors: missing commas, trailing commas
  15. fixed_string = json_string.replace('}{', '},{') #Fixes trailing commas
  16. fixed_string = re.sub(r',}', ')', fixed_string) #Fixes missing commas
  17. try:
  18. data = json.loads(fixed_string)
  19. return data # Return if fixed JSON
  20. except json.JSONDecodeError as e2:
  21. print(f"Fixing JSON decode error: {e2}")
  22. return None # Return None if fixing fails
  23. if __name__ == '__main__':
  24. #Example Usage
  25. #Valid JSON
  26. valid_json = '{"name": "John", "age": 30}'
  27. fixed_data = fix_json(valid_json)
  28. if fixed_data:
  29. print(f"Valid JSON fixed: {fixed_data}")
  30. #JSON with trailing comma
  31. trailing_comma_json = '{"name": "John", "age": 30,}'
  32. fixed_data = fix_json(trailing_comma_json)
  33. if fixed_data:
  34. print(f"Trailing comma JSON fixed: {fixed_data}")
  35. #JSON with missing comma
  36. missing_comma_json = '{"name": "John" "age": 30}'
  37. fixed_data = fix_json(missing_comma_json)
  38. if fixed_data:
  39. print(f"Missing comma JSON fixed: {fixed_data}")
  40. #Invalid JSON
  41. invalid_json = '{"name": "John", "age": 30'
  42. fixed_data = fix_json(invalid_json)
  43. if fixed_data is None:
  44. print("Invalid JSON not fixed.")

Add your comment