Last active
September 28, 2021 07:11
-
-
Save Sheikh2Imran/afaef1c02494ca764183e57f03bf8ca8 to your computer and use it in GitHub Desktop.
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 ast | |
| import json | |
| def parse_json_string(text, default={}): | |
| """ | |
| function to parse the json string | |
| into json parse or dict | |
| :param `text` is the value of text model to parse. | |
| :paran `default` is default output, eg: {}, [] | |
| :return json loads or dict. | |
| """ | |
| output = default | |
| if not text: | |
| return default | |
| if isinstance(text, list) or isinstance(text, dict): | |
| return text | |
| try: | |
| output = json.loads(text) | |
| except json.decoder.JSONDecodeError: | |
| try: | |
| output = ast.literal_eval(text) | |
| except Exception: | |
| # invalid format | |
| pass | |
| if type(default) == type(output): | |
| return output | |
| return default |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment