Write me a python function called fix_json that fixes broken JSON objects, and returns the parsed object. I'll pass the JSON object as a string and it should fix: - Incorect parenthesis, e.g., {"a": (5, 4)} -> {"a": [5, 4]} - Incorrect single quotes, e.g., {'a': 5} -> {"a": 5} - False/True -> false/true Make sure not to break data inside strings! So if there's a True or a ( inside a string keep them the way they are. Also don't break quoted strings
Write me a python function called fix_json that fixes broken JSON objects, and returns the parsed object. I'll pass the JSON object as a string and it should fix: - Incorect parenthesis, e.g., {"a": (5, 4)} -> {"a": [5, 4]} - Incorrect single quotes, e.g., {'a': 5} -> {"a": 5} - False/True -> false/true Make sure not to break data inside strings! So if there's a True or a ( inside a string keep them the way they are. Also don't break quoted strings
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | import re import json def fix_json(json_str): """ Fixes broken JSON objects and returns the parsed object. Args: json_str (str): The broken JSON object as a string. Returns: dict: The parsed JSON object. """ # Replace incorrect single quotes with double quotes json_str = re.sub(r"([a-zA-Z0-9_]+):", r'"\1":', json_str) # Replace incorrect parentheses with brackets json_str = re.sub(r"(\w+):\s*\(([^)]+)\)", r'\1: [\2]', json_str) # Replace incorrect boolean values json_str = re.sub(r"\b(True|False)\b", lambda match: match.group(0).lower(), json_str) # Replace incorrect single quotes inside objects json_str = re.sub(r"(\{|\[|\s):'([^']*)'", r'\1"\2"', json_str) json_str = re.sub(r"'([^']*)'(\s|\]|})", r'"\1"\2', json_str) # Parse the fixed JSON object try: return json.loads(json_str) except json.JSONDecodeError as e: print(f"Error parsing JSON: {e}") return None # Example usage: broken_json = "{'a': (5, 4), 'b': True, 'c': 'This is a string with (parens) and True'}" fixed_json = fix_json(broken_json) print(fixed_json) |
I extracted the following code from that output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | import re import json def fix_json(json_str): """ Fixes broken JSON objects and returns the parsed object. Args: json_str (str): The broken JSON object as a string. Returns: dict: The parsed JSON object. """ # Replace incorrect single quotes with double quotes json_str = re.sub(r"([a-zA-Z0-9_]+):", r'"\1":', json_str) # Replace incorrect parentheses with brackets json_str = re.sub(r"(\w+):\s*\(([^)]+)\)", r'\1: [\2]', json_str) # Replace incorrect boolean values json_str = re.sub(r"\b(True|False)\b", lambda match: match.group(0).lower(), json_str) # Replace incorrect single quotes inside objects json_str = re.sub(r"(\{|\[|\s):'([^']*)'", r'\1"\2"', json_str) json_str = re.sub(r"'([^']*)'(\s|\]|})", r'"\1"\2', json_str) # Parse the fixed JSON object try: return json.loads(json_str) except json.JSONDecodeError as e: print(f"Error parsing JSON: {e}") return None # Example usage: broken_json = "{'a': (5, 4), 'b': True, 'c': 'This is a string with (parens) and True'}" fixed_json = fix_json(broken_json) print(fixed_json) |
Running the following program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | import re import json def fix_json(json_str): """ Fixes broken JSON objects and returns the parsed object. Args: json_str (str): The broken JSON object as a string. Returns: dict: The parsed JSON object. """ # Replace incorrect single quotes with double quotes json_str = re.sub(r"([a-zA-Z0-9_]+):", r'"\1":', json_str) # Replace incorrect parentheses with brackets json_str = re.sub(r"(\w+):\s*\(([^)]+)\)", r'\1: [\2]', json_str) # Replace incorrect boolean values json_str = re.sub(r"\b(True|False)\b", lambda match: match.group(0).lower(), json_str) # Replace incorrect single quotes inside objects json_str = re.sub(r"(\{|\[|\s):'([^']*)'", r'\1"\2"', json_str) json_str = re.sub(r"'([^']*)'(\s|\]|})", r'"\1"\2', json_str) # Parse the fixed JSON object try: return json.loads(json_str) except json.JSONDecodeError as e: print(f"Error parsing JSON: {e}") return None # Example usage: broken_json = "{'a': (5, 4), 'b': True, 'c': 'This is a string with (parens) and True'}" fixed_json = fix_json(broken_json) print(fixed_json) answer = fix_json('''{"a": 5, "b": [3, 4]}''') expected = {"a": 5, "b": [3, 4]} assert answer == expected, f'Wrong answer; got {answer} instead of {expected}' answer = fix_json('''{'a': 5.0, 'b': (True, 4)}''') expected = {"a": 5.0, "b": [True, 4]} assert answer == expected, f'Wrong answer; got {answer} instead of {expected}' answer = fix_json('''{'True': False, 'b()': (3, 4), "c'": []}''') expected = {"True": False, "b()": [3, 4], "c'": []} assert answer == expected, f'Wrong answer; got {answer} instead of {expected}' print('All tests passed') |
Error parsing JSON: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
None
Error parsing JSON: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
Traceback (most recent call last):
File "/usr/src/app/main.py", line 51, in <module>
assert answer == expected, f'Wrong answer; got {answer} instead of {expected}'
^^^^^^^^^^^^^^^^^^
AssertionError: Wrong answer; got None instead of {'a': 5.0, 'b': [True, 4]}
Testing if the previous output contains the string All tests passed
: False