-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcheck_recover_json.py
71 lines (62 loc) · 2.04 KB
/
check_recover_json.py
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#!/usr/bin/python
# -*- coding: utf-8 -*-
from question import get_response
from json_utils import parse_json
import json
import traceback
def check_json_str(json_data: str):
try:
_ = json.loads(json_data)
return (True, "OK")
except json.JSONDecodeError as e:
traceback_str = traceback.format_exc()
error_message = f"ERROR: {str(e)}"
print(traceback_str + error_message)
return (False, error_message)
def check_json(filepath: str):
try:
with open(filepath, "r") as file:
json_data = json.load(file)
return (True, "OK")
except json.JSONDecodeError as e:
traceback_str = traceback.format_exc()
error_message = f"ERROR: {str(e)}"
print(traceback_str + error_message)
return (False, error_message)
def recover_json_str(errcode, data: str):
res = get_response(f"{errcode}\nPlease fix this json data:\n {data}")
json_data = parse_json(res)
return json_data
def recover_json(errcode, filepath: str):
with open(filepath, "r") as file:
data = file.read()
json_data = recover_json_str(errcode, data)
result, _ = check_json_str(json_data)
return (result, json_data)
if __name__ == "__main__":
import sys
if len(sys.argv) != 2:
print("Usage: <filepath>")
sys.exit(1)
filepath = sys.argv[1]
count = 1
while True:
result, errcode = check_json(filepath)
if result == False:
result, json_data = recover_json(errcode, filepath)
if result == True:
with open(filepath, "w") as file:
file.write(json_data)
print("INFO: RECOVERED JSON DATA")
break
elif count <= 5:
print("ERROR: RCOVERING JSON DATA: RETRY_COUNT=", count)
count += 1
else:
print(json_data)
print("ERROR: can not recover json data...")
sys.exit(1)
else:
break
print("OK")
sys.exit(0)