Skip to content

Commit 9208c9c

Browse files
Fix extract_json docstring
1 parent 7b86a49 commit 9208c9c

File tree

1 file changed

+11
-10
lines changed

1 file changed

+11
-10
lines changed

shared/python/utils.py

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -338,31 +338,32 @@ def cleanup_resources(deployment: str | INFRASTRUCTURE, rg_name: str ) -> None:
338338

339339
def extract_json(text: str) -> any:
340340
"""
341-
Extract the first valid JSON object or array from a string and return it as a JSON string.
342-
Uses json.JSONDecoder().raw_decode to robustly parse the first JSON object or array found in the string. The JSON object may be buried in the string and have preceding or trailing regular text.
341+
Extract the first valid JSON object or array from a string and return it as a Python object.
342+
343+
This function searches the input string for the first occurrence of a JSON object or array (delimited by '{' or '['),
344+
and attempts to decode it using json.JSONDecoder().raw_decode. If the input is already valid JSON, it is returned as a Python object.
345+
If no valid JSON is found, None is returned.
343346
344347
Args:
345-
text (str): The string to search for JSON.
348+
text (str): The string to search for a JSON object or array.
346349
347350
Returns:
348-
str | None: The extracted JSON as a string, or None if not found.
351+
Any | None: The extracted JSON as a Python object (dict or list), or None if not found or not valid.
349352
"""
350353

351354
if not isinstance(text, str):
352355
return None
353-
354-
# If the string is already JSON, return it.
355-
if is_string_json(text):
356-
return text
357356

358-
print(text)
357+
# If the string is already valid JSON, parse and return it as a Python object.
358+
if is_string_json(text):
359+
return json.loads(text)
359360

360361
decoder = json.JSONDecoder()
361362

362363
for start in range(len(text)):
363364
if text[start] in ('{', '['):
364365
try:
365-
obj, end = decoder.raw_decode(text[start:])
366+
obj, _ = decoder.raw_decode(text[start:])
366367
return obj
367368
except Exception:
368369
continue

0 commit comments

Comments
 (0)