Skip to content

Instantly share code, notes, and snippets.

@gsscoder
Last active November 21, 2019 13:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gsscoder/e212d1630bc4e7f036c63411b1262116 to your computer and use it in GitHub Desktop.
Save gsscoder/e212d1630bc4e7f036c63411b1262116 to your computer and use it in GitHub Desktop.
Turns a javascript dictionary into a JSON string
# 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