Skip to content

Instantly share code, notes, and snippets.

@konverner
Created September 23, 2024 19:42
Show Gist options
  • Save konverner/00d7d0673ae72686ecd133ccb9013151 to your computer and use it in GitHub Desktop.
Save konverner/00d7d0673ae72686ecd133ccb9013151 to your computer and use it in GitHub Desktop.
Extract json content from markdown content
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