Skip to content

Instantly share code, notes, and snippets.

@pjaol
Created November 9, 2023 23:30
Show Gist options
  • Save pjaol/5360acdb157c0238ef78ebbbde7d07cc to your computer and use it in GitHub Desktop.
Save pjaol/5360acdb157c0238ef78ebbbde7d07cc to your computer and use it in GitHub Desktop.
import json
def extract_json(text):
"""
Extracts JSON objects or arrays from a given text, including nested structures.
:param text: A string containing mixed content with JSON objects or arrays.
:return: A list of extracted JSON objects or arrays.
"""
json_objects = []
stack = []
start_idx = None
for i, char in enumerate(text):
if char in '{[':
if not stack:
start_idx = i # Potential start of a JSON object/array
stack.append(char)
elif char in '}]':
if stack:
stack.pop()
if not stack:
# Potential end of a JSON object/array
try:
json_obj = json.loads(text[start_idx:i+1])
json_objects.append(json_obj)
except json.JSONDecodeError:
pass # Not a valid JSON, ignore
return json_objects
response="""Sure! Here are the nutritional values for 100g of red cabbage in JSON format:
Sure! Here are the nutritional values for 100g of red cabbage in JSON format:
{
"ingredient": "red cabbage",
"protein": {
"value": 2.6,
"unit": "mg"
},
"fat": {
"value": 0.3,
"unit": "mg"
},
"oxalate": {
"value": 1.4,
"unit": "mg"
},
"sulfate": {
"value": 0.2,
"unit": "mg"
}
}
"""
print(extract_json(result))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment