import json
def batch_json_dry_run(json_responses, operations):
"""
Performs batch operations on a list of JSON responses for dry-run scenarios.
Args:
json_responses (list): A list of JSON strings or dictionaries.
operations (list): A list of operations to perform on each JSON response.
Each operation is a dictionary with 'type' and 'value' keys.
'type' can be 'replace', 'add', or 'remove'.
'value' contains the operation's details.
Returns:
list: A list of modified JSON responses (strings or dictionaries).
"""
modified_responses = []
for i, response in enumerate(json_responses):
try:
# Load JSON if it's a string
if isinstance(response, str):
data = json.loads(response)
else:
data = response # Assume it's already a dictionary
for operation in operations:
operation_type = operation['type']
if operation_type == 'replace':
# Replace a key's value
key = operation['value']['key']
new_value = operation['value']['value']
if key in data:
data[key] = new_value
else:
print(f"Warning: Key '{key}' not found in response {i+1}")
elif operation_type == 'add':
# Add a new key-value pair
key = operation['value']['key']
value = operation['value']['value']
data[key] = value
elif operation_type == 'remove':
# Remove a key
key = operation['value']['key']
if key in data:
del data[key]
else:
print(f"Warning: Key '{key}' not found in response {i+1}")
else:
print(f"Warning: Unknown operation type '{operation_type}'")
# Convert back to JSON string if the original was a string
if isinstance(response, str):
modified_responses.append(json.dumps(data, indent=4)) # indent for readability
else:
modified_responses.append(data)
except json.JSONDecodeError:
print(f"Error decoding JSON in response {i+1}")
modified_responses.append(response) #Return original if decode fails.
except Exception as e:
print(f"An unexpected error occurred while processing response {i+1}: {e}")
modified_responses.append(response) #Return original if any other error.
return modified_responses
if __name__ == '__main__':
# Example usage
json_responses = [
'{"name": "Alice", "age": 30}',
{"city": "New York", "population": 8400000}
]
operations = [
{'type': 'replace', 'value': {'key': 'age', 'value': 31}},
{'type': 'add', 'value': {'key': 'occupation', 'value': 'Engineer'}},
{'type': 'remove', 'value': {'key': 'population'}} #remove population from the second response
]
modified_responses = batch_json_dry_run(json_responses, operations)
for i, response in enumerate(modified_responses):
print(f"Modified Response {i+1}:\n{response}\n")
Add your comment