Created
April 25, 2016 21:56
-
-
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.
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 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