import json
def nest_json(data):
"""
Nests JSON payloads into a hierarchical structure with basic validation.
"""
if not isinstance(data, (dict, list)):
raise ValueError("Input must be a dictionary or a list.")
if isinstance(data, dict):
nested_data = {}
for key, value in data.items():
if not isinstance(key, str):
raise ValueError("Keys must be strings.")
nested_data[key] = nest_json(value)
return nested_data
elif isinstance(data, list):
return [nest_json(item) for item in data]
else:
return data # Return primitive values as is
if __name__ == '__main__':
# Example usage
json_data = {
"name": "John Doe",
"age": 30,
"address": {
"street": "123 Main St",
"city": "Anytown",
"zip": "12345"
},
"phoneNumbers": [
{"type": "home", "number": "555-123-4567"},
{"type": "work", "number": "555-987-6543"}
]
}
try:
nested_json_data = nest_json(json_data)
print(json.dumps(nested_json_data, indent=4))
except ValueError as e:
print(f"Error: {e}")
#Example with list as root
list_data = [1,2,{"a":3, "b":4}]
try:
nested_list_data = nest_json(list_data)
print(json.dumps(nested_list_data, indent=4))
except ValueError as e:
print(f"Error: {e}")
Add your comment