def extractJson(message: str) -> Optional[Mapping]:
""" Returns the first json blob found in the string if any are found """
# First pass that relies on it being in a code block
for match in re.findall('\`\s*?{[\s\S]*?}\s*?\`', message):
potJson = match[1:-1].strip()
try:
return json.loads(potJson)
except ValueError:
pass
# Second pass doesn't require the code block, but it still uses the json parser
for match in re.findall('{[\s\S]*}', message):
try:
return json.loads(match)
except ValueError:
pass
# Third pass uses ast.literal_eval (which IS safe-it only evals literals) and some replacements to handle malformed
# JSON. This is a horrible JSON parser and will incorrectly parse certain types of JSON, but it is far more
# accepting so we might as well try doing this
for match in re.findall('{[\s\S]*}', message):
try:
return fuzzyJsonParse(match)
except (SyntaxError, ValueError):
pass
return None
评论列表
文章目录