Skip to content

Instantly share code, notes, and snippets.

@Sheikh2Imran
Last active September 28, 2021 07:11
Show Gist options
  • Select an option

  • Save Sheikh2Imran/afaef1c02494ca764183e57f03bf8ca8 to your computer and use it in GitHub Desktop.

Select an option

Save Sheikh2Imran/afaef1c02494ca764183e57f03bf8ca8 to your computer and use it in GitHub Desktop.
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