import json
import re
def match_json_pattern(json_string, patterns):
"""
Matches a JSON string against a list of regular expression patterns.
Args:
json_string (str): The JSON string to match.
patterns (dict): A dictionary where keys are pattern names and values are regular expression strings.
Returns:
dict: A dictionary containing the matched pattern names and their corresponding matches.
Returns an empty dictionary if no patterns match.
"""
matches = {}
try:
data = json.loads(json_string) # Parse the JSON string
except json.JSONDecodeError:
return {} # Return empty dict if JSON is invalid
for pattern_name, pattern in patterns.items():
try:
match = re.search(pattern, json_string, re.DOTALL) # Search for the pattern
if match:
matches[pattern_name] = match.group(0) # Store the matched string
except re.error as e:
print(f"Invalid regex pattern '{pattern_name}': {e}") #Report invalid regex patterns
return matches
if __name__ == '__main__':
# Example usage
patterns = {
"error_message": r'"error": "(.*)"', # Matches JSON with an "error" field containing a string
"status_code": r'"status": (\d+)', # Matches JSON with a "status" field containing a number
"user_id": r'"user_id": (\d+)' #Matches JSON with a user_id field containing a number
}
# Test JSON strings
json_strings = [
'{"error": "Invalid input"}',
'{"status": 200}',
'{"user_id": 123}',
'{"message": "Success"}',
'{"status": "success"}' #This will not match status_code
]
for json_string in json_strings:
matched_patterns = match_json_pattern(json_string, patterns)
print(f"JSON: {json_string}")
print(f"Matched Patterns: {matched_patterns}")
print("-" * 20)
Add your comment