Created
May 29, 2020 18:14
-
-
Save Sasszem/bebb6b248d5cab5df57df2d3810471fd to your computer and use it in GitHub Desktop.
Extract JSON from text - a quick-and-dirty iterator. Handles braces in strings and escapes (possibly).
This file contains 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
def extractJSON(string): | |
extracted = "" | |
seen = 0 | |
in_string = False | |
escape = False | |
for char in string: | |
if char=="{" and not in_string: | |
seen += 1 | |
if seen>0: | |
extracted += char | |
if char=="\"" and not escape: | |
in_string = not in_string | |
if char=="}": | |
if not in_string and not escape: | |
seen -= 1 | |
if seen==0: | |
yield extracted | |
extracted = "" | |
if char=="\\" and in_string and not escape: | |
escape = True | |
else: | |
escape = False | |
if __name__=="__main__": | |
testString = """ | |
random junk here | |
{ | |
"key1": "value1", | |
"key1": "value1", | |
"nested": { | |
"nested key": "true" | |
} | |
} | |
Other random junk | |
{ | |
"sneaky lil value": "{{{}}}}}}", | |
"sneaky key }{}{}}}{\\"\\"\\\\": false | |
} | |
Ends here | |
""" | |
print(testString) | |
from json import loads | |
for j in extractJSON(testString): | |
print(loads(j)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment