|
93 | 93 | print(f"Timeout: {config['timeout']} seconds") |
94 | 94 | print(f"Logging: {'Enabled' if config['enable_logging'] else 'Disabled'}") |
95 | 95 |
|
| 96 | + |
| 97 | +def parse_json_safely(json_string): |
| 98 | + try: |
| 99 | + return json.loads(json_string) |
| 100 | + except json.JSONDecodeError as e: |
| 101 | + print(f"JSON parsing failed: {e.msg}") |
| 102 | + print(f"Error at line {e.lineno}, column {e.colno}") |
| 103 | + return None |
| 104 | + |
| 105 | +# Missing closing quote |
| 106 | +bad_json1 = '{"name": "Sarah, "age": 28}' |
| 107 | +result1 = parse_json_safely(bad_json1) |
| 108 | +print(f"Result 1: {result1}\n") |
| 109 | + |
| 110 | +# Missing closing brace |
| 111 | +bad_json2 = '{"name": "Sarah", "age": 28' |
| 112 | +result2 = parse_json_safely(bad_json2) |
| 113 | +print(f"Result 2: {result2}\n") |
| 114 | + |
| 115 | +# Extra comma |
| 116 | +bad_json3 = '{"name": "Sarah", "age": 28,}' |
| 117 | +result3 = parse_json_safely(bad_json3) |
| 118 | +print(f"Result 3: {result3}\n") |
| 119 | + |
| 120 | +# Valid JSON for comparison |
| 121 | +good_json = '{"name": "Sarah", "age": 28}' |
| 122 | +result4 = parse_json_safely(good_json) |
| 123 | +print(f"Result 4: {result4}") |
| 124 | + |
| 125 | +def load_json_file_safely(filepath): |
| 126 | + try: |
| 127 | + with open(filepath, 'r') as f: |
| 128 | + return json.load(f) |
| 129 | + except FileNotFoundError: |
| 130 | + print(f"Error: File '{filepath}' not found") |
| 131 | + return None |
| 132 | + except PermissionError: |
| 133 | + print(f"Error: Permission denied reading '{filepath}'") |
| 134 | + return None |
| 135 | + except json.JSONDecodeError as e: |
| 136 | + print(f"Error: Invalid JSON in '{filepath}'") |
| 137 | + print(f" {e.msg} at line {e.lineno}") |
| 138 | + return None |
| 139 | + |
| 140 | +data = load_json_file_safely('missing_file.json') |
| 141 | +if data is None: |
| 142 | + print("Using default configuration") |
| 143 | + data = {"timeout": 30, "retries": 3} |
0 commit comments