You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
343
346
344
347
Args:
345
-
text (str): The string to search for JSON.
348
+
text (str): The string to search for a JSON object or array.
346
349
347
350
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.
349
352
"""
350
353
351
354
ifnotisinstance(text, str):
352
355
returnNone
353
-
354
-
# If the string is already JSON, return it.
355
-
ifis_string_json(text):
356
-
returntext
357
356
358
-
print(text)
357
+
# If the string is already valid JSON, parse and return it as a Python object.
0 commit comments