Last active
November 21, 2019 13:49
-
-
Save gsscoder/e212d1630bc4e7f036c63411b1262116 to your computer and use it in GitHub Desktop.
Turns a javascript dictionary into a 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
# jsonify('{ hello: "json", hello_again: { from: ["java", "script"]}}') | |
# '{ "hello": "json", "hello_again": { "from": ["java", "script"]}}' | |
# note: before calling better use https://github.com/beautify-web/js-beautify | |
def jsonify(js_dict_code): | |
json_string = js_dict_code | |
matches = re.findall(r'(?<![\S"])([^"\s{}\[\],]+:)(?![\S"])', js_dict_code) | |
if matches: | |
for unquoted in matches: | |
quoted = f'"{unquoted.strip()[:-1]}": ' | |
json_string = json_string.replace(unquoted, quoted, 1) | |
return json_string |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment