Created
March 20, 2025 13:55
-
-
Save ArthurDelannoyazerty/38b62c702a9a200ccd3d011c5394f473 to your computer and use it in GitHub Desktop.
Extract a json/dict from a string in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import logging | |
logger = logging.getLogger(__name__) | |
def extract_json_from_string(text:str) -> dict: | |
"""Convert a text containing a JSON or python dict into a python dict. | |
:param str text: | |
:raises ValueError: If the string does not contains a valid json | |
:return dict: | |
""" | |
start_dict = text.find('{') | |
end_dict = text.rfind('}') | |
# Check if dict boundaries are valid | |
if start_dict == -1 or end_dict == -1: | |
logger.warning( 'JSON wrong format : the string do not have opening or closing bracket. (missing "{" or "}")') | |
raise ValueError('JSON wrong format : the string do not have opening or closing bracket. (missing "{" or "}")') | |
dict_string = text[start_dict:end_dict+1] | |
try: | |
extracted_dict = eval(dict_string) | |
logger.debug(f'Extracted JSON (`eval()`) : {extracted_dict}') | |
except: | |
try: | |
import json | |
extracted_dict = json.loads(dict_string) | |
logger.debug(f'Extracted JSON (`json.loads()`) : {extracted_dict}') | |
except Exception as e: | |
logger.exception(f'Error during the conversion from a string of a dict to a python dict. dict_string : {dict_string}') | |
raise ValueError(f'Error during the conversion from a string of a dict to a python dict. dict_string : {dict_string}') | |
return extracted_dict | |
if __name__=="__main__": | |
string_dict = """ | |
{ | |
'f1': 'string here', | |
'f2': 1234, | |
'f3': None, | |
'f4': 'null' | |
} | |
""" | |
print(extract_json_from_string(string_dict)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment