import json
def split_json_data(json_data, split_size, version=""):
"""Splits a JSON object into smaller JSON objects for development.
Args:
json_data (str or dict): The JSON data to split. Can be a JSON string or a dictionary.
split_size (int): The maximum size (in number of key-value pairs) of each split JSON object.
version (str, optional): Version string for compatibility. Defaults to "".
Returns:
list: A list of JSON strings, each representing a split object. Returns an empty list if input is invalid.
"""
if not json_data:
return []
try:
if isinstance(json_data, str):
data = json.loads(json_data)
elif isinstance(json_data, dict):
data = json_data
else:
return [] # Invalid input type
if not isinstance(data, dict):
return [] #JSON data must be an object
split_list = []
current_split = {}
count = 0
for key, value in data.items():
current_split[key] = value
count += 1
if count >= split_size:
split_list.append(json.dumps(current_split, indent=4)) # Convert to JSON string
current_split = {}
count = 0
if current_split:
split_list.append(json.dumps(current_split, indent=4)) # Add the last split
return split_list
except json.JSONDecodeError:
print("Invalid JSON format.")
return []
except Exception as e:
print(f"An error occurred: {e}")
return []
Add your comment