Skip to content

Instantly share code, notes, and snippets.

@sytrus-in-github
Created April 25, 2016 21:56
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 sytrus-in-github/4930a6eb381ca24a9dfcef732ef93644 to your computer and use it in GitHub Desktop.
Save sytrus-in-github/4930a6eb381ca24a9dfcef732ef93644 to your computer and use it in GitHub Desktop.
A python script to transform JSON data file to JavaScript file so that the data can be loaded on local machine with <script> tag. A browser-independent workaround of local JSON file access problem.
import json
def json2js(jsonfilepath, functionname='getData'):
"""function converting json file to javascript file: json_data -> json_data.js
:param jsonfilepath: path to json file
:param functionname: name of javascript function which will return the data
:return None
"""
# load json data
with open(jsonfilepath,'r') as jsonfile:
data = json.load(jsonfile)
# write transformed javascript file
with open(jsonfilepath+'.js', 'w') as jsfile:
jsfile.write('function '+functionname+'(){return ')
jsfile.write(json.dumps(data))
jsfile.write(';}')
if __name__ == '__main__':
from sys import argv
l = len(argv)
if l == 2:
json2js(argv[1])
elif l == 3:
json2js(argv[1], argv[2])
else:
raise ValueError('Correct syntax: python pathTo/json2js.py jsonfilepath [jsfunctionname]')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment