1. import json
  2. def diagnose_json(json_data):
  3. """
  4. Imports JSON data and provides simple error messages if parsing fails.
  5. """
  6. try:
  7. data = json.loads(json_data) # Parse JSON string to Python object
  8. except json.JSONDecodeError as e:
  9. print(f"Error decoding JSON: {e}") # Print error message if parsing fails
  10. return None # Return None if parsing fails
  11. # Process the parsed JSON data here if needed.
  12. # For example, you could access specific fields:
  13. # if 'error' in data:
  14. # print(f"Diagnostic error: {data['error']}")
  15. return data # Return the parsed JSON data if successful
  16. if __name__ == '__main__':
  17. # Example Usage
  18. valid_json = '{"status": "success", "message": "Diagnostics completed"}'
  19. invalid_json = '{"status": "error", "message": "Invalid JSON" ' # Missing closing brace
  20. diagnostics_data = diagnose_json(valid_json)
  21. if diagnostics_data:
  22. print("Diagnostics data received:")
  23. print(diagnostics_data)
  24. diagnostics_data = diagnose_json(invalid_json)
  25. if diagnostics_data is None:
  26. print("Diagnostics failed to process invalid JSON.")

Add your comment