Skip to content

Instantly share code, notes, and snippets.

@ngenieer
Last active November 4, 2021 01:37
Show Gist options
  • Select an option

  • Save ngenieer/821ef9b8a8d459a10a0fd0b58b787c69 to your computer and use it in GitHub Desktop.

Select an option

Save ngenieer/821ef9b8a8d459a10a0fd0b58b787c69 to your computer and use it in GitHub Desktop.
strip any unnecessary characters from string to make it a json string
def strip_for_json(jstr):
"""
strip any unnecessary characters from string
to make it a json string.
does not garantee the returened string is a real json string.
just for next process.
"""
occupied = [('[',']'),('{','}')]
couples = [('(',')'),('<','>')]
for firstC,lastC in occupied:
jstr = jstr.strip()
if jstr[0]==firstC and jstr[-1]==lastC:
return jstr
for firstC,lastC in couples:
jstr = jstr.strip()
if jstr[0]==firstC and jstr[-1]==lastC:
jstr = jstr[1:]
jstr = jstr[:-1]
while True:
jstr = jstr.strip()
if jstr[0] == jstr[-1]:
jstr = jstr[1:]
jstr = jstr[:-1]
else:
break
return strip_for_json(jstr)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment