1. import json
  2. def compact_json(json_string):
  3. """
  4. Compact JSON string for easier testing and sanity checks.
  5. """
  6. try:
  7. data = json.loads(json_string) # Parse the JSON string
  8. compact_json = json.dumps(data, separators=(',', ':')) # Use compact separators
  9. return compact_json
  10. except json.JSONDecodeError:
  11. return "Invalid JSON" #Handle invalid JSON input
  12. if __name__ == '__main__':
  13. #Example Usage
  14. test_json = """
  15. {
  16. "name": "John Doe",
  17. "age": 30,
  18. "city": "New York",
  19. "hobbies": ["reading", "hiking", "coding"],
  20. "address": {
  21. "street": "123 Main St",
  22. "zipcode": "10001"
  23. }
  24. }
  25. """
  26. compacted_json = compact_json(test_json)
  27. print(compacted_json)
  28. invalid_json = "This is not JSON"
  29. compacted_invalid = compact_json(invalid_json)
  30. print(compacted_invalid)

Add your comment