quiz-generator / utils.py
Abdullah Khan Kakar
feat: PDF URL input for topic extraction, title generation, fix parse_json for objects
0705f93
Raw
History Blame Contribute Delete
1.29 kB
import json
import re
def parse_json(response):
cleaned = response.strip()
if cleaned.startswith("```"):
cleaned = re.sub(r"^```\w*\n?", "", cleaned)
cleaned = re.sub(r"\n```$", "", cleaned)
obj_start = cleaned.find("{")
arr_start = cleaned.find("[")
if obj_start != -1 and (arr_start == -1 or obj_start < arr_start):
depth = 0
end = obj_start
for i in range(obj_start, len(cleaned)):
if cleaned[i] == "{":
depth += 1
elif cleaned[i] == "}":
depth -= 1
if depth == 0:
end = i + 1
break
json_string = cleaned[obj_start:end]
elif arr_start != -1:
depth = 0
end = arr_start
for i in range(arr_start, len(cleaned)):
if cleaned[i] == "[":
depth += 1
elif cleaned[i] == "]":
depth -= 1
if depth == 0:
end = i + 1
break
json_string = cleaned[arr_start:end]
else:
raise ValueError("No JSON object or array found")
print("====== JSON STRING ======")
print(json_string)
print("=========================")
return json.loads(json_string)