1. import json
  2. def split_json_data(json_data, split_size, version=""):
  3. """Splits a JSON object into smaller JSON objects for development.
  4. Args:
  5. json_data (str or dict): The JSON data to split. Can be a JSON string or a dictionary.
  6. split_size (int): The maximum size (in number of key-value pairs) of each split JSON object.
  7. version (str, optional): Version string for compatibility. Defaults to "".
  8. Returns:
  9. list: A list of JSON strings, each representing a split object. Returns an empty list if input is invalid.
  10. """
  11. if not json_data:
  12. return []
  13. try:
  14. if isinstance(json_data, str):
  15. data = json.loads(json_data)
  16. elif isinstance(json_data, dict):
  17. data = json_data
  18. else:
  19. return [] # Invalid input type
  20. if not isinstance(data, dict):
  21. return [] #JSON data must be an object
  22. split_list = []
  23. current_split = {}
  24. count = 0
  25. for key, value in data.items():
  26. current_split[key] = value
  27. count += 1
  28. if count >= split_size:
  29. split_list.append(json.dumps(current_split, indent=4)) # Convert to JSON string
  30. current_split = {}
  31. count = 0
  32. if current_split:
  33. split_list.append(json.dumps(current_split, indent=4)) # Add the last split
  34. return split_list
  35. except json.JSONDecodeError:
  36. print("Invalid JSON format.")
  37. return []
  38. except Exception as e:
  39. print(f"An error occurred: {e}")
  40. return []

Add your comment