Created
September 23, 2024 19:42
-
-
Save konverner/00d7d0673ae72686ecd133ccb9013151 to your computer and use it in GitHub Desktop.
Extract json content from markdown content
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
def extract_json_from_text(text): | |
# Find the first '{' character | |
start = text.find('{') | |
if start == -1: | |
print("No JSON block found in the text.") | |
return None | |
# Use a stack to track nested braces | |
stack = [] | |
for i in range(start, len(text)): | |
if text[i] == '{': | |
stack.append(i) | |
elif text[i] == '}': | |
stack.pop() | |
if not stack: | |
end = i + 1 | |
break | |
else: | |
print("No complete JSON block found in the text.") | |
return None | |
json_str = text[start:end] | |
try: | |
# Convert JSON string to dictionary | |
json_dict = json.loads(json_str) | |
return json_dict | |
except json.JSONDecodeError as e: | |
print(f"Error decoding JSON: {e}") | |
return None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment