Created
July 28, 2018 20:16
-
-
Save v1k45/8f7742d0cfb7ac6c1fccd130d8da0e76 to your computer and use it in GitHub Desktop.
hack to convert js object to json string
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
import re | |
import json | |
PRIMITIVE_DATA_GROUPER = r"(?P<initiator>\{|)(\s|)(?P<key>\w+):(\"|)(?P<value>(\B|[\w\s:-]+|\w+\((\"|)\w+(\"|)\)|function\(\)\{[\s\w\"\?\=:-]+\}))(\"|)(?P<terminator>,|\}|\},|\s,)" | |
OBJECT_DATA_GROUPER = r"(?P<key>\w+):(?P<identifier_token>(\{|\[))" | |
def get_data(): | |
with open("data") as f: | |
content = f.read() | |
return content | |
def strip(content): | |
return re.sub("[\\n\\t]+", "", content) | |
def stringify_content(content): | |
def replace_primitives(match_obj): | |
group_dict = match_obj.groupdict() | |
group_dict["key"] = '"%s"' % group_dict["key"] | |
if not group_dict["value"].startswith('"'): | |
group_dict["value"] = json.dumps(group_dict["value"]) | |
return "{initiator}{key}:{value}{terminator}".format(**group_dict) | |
replaced_content = re.sub(PRIMITIVE_DATA_GROUPER, replace_primitives, content) | |
return re.sub(OBJECT_DATA_GROUPER, '"\g<key>":\g<identifier_token>', replaced_content) | |
def main(): | |
content = strip(get_data()) | |
with open("data_1", "w") as f: | |
f.write(stringify_content(content)) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment