0

I am supposed to read one Python data structure, a 2d list to be precise into a javascript function. I came to know that this could be done after converting the python data structure into a json object and then reading the json object back using Javascript function. I am rendering the html page using the Python script as you can see below.

import webbrowser, json
f = open('World.html', 'w') 
arr = [[]]
arr[0].append('Hello')
arr[0].append('There')
arr.append([])
arr[1].append('Good')
arr[1].append('Morning')
arr[1].append('!')
message = '''<html><head><script type="text/javascript" src="outputjson.json"></script><script>function Hello(){alert(outputjson.arr);}</script></head><body><h1>This is not working and you know it</h1><input value="Click Bro" type="button" onclick="Hello();"></input></body></html>'''
f.write(message)
with open('outputjson.json', 'w') as f:
        json.dump(arr, f)

f.close()
webbrowser.open_new_tab('World.html')

Outputjson.json look something like this: [["Hello", "There"], ["Good", "Morning", "!"]]

The json object is successfully created but I am unable to read it back through my javascript function. Where am I going wrong ? I have a constraint, I can't go for BeautifulSoup. Thanks in advance.

jyotirmaya ojha
  • 73
  • 1
  • 13

1 Answers1

0

You can't simple load json file into browser like that. One way is to make a XHR request to the json file and load it. The other way is to convert your json to jsonp structure.

jsonp_structure = "hello(" + json.dumps(arr) + ")"
f.write(jsonp_structure)

With the above change your hello javascript function will get called with the JSON. You can choose to store the JSON for further access/processing.

bugs_cena
  • 495
  • 5
  • 11
  • Refer to this answer for jsonp: https://stackoverflow.com/questions/3839966/can-anyone-explain-what-jsonp-is-in-layman-terms – bugs_cena Jun 02 '17 at 06:15
  • Hey thanks for the suggestion, it worked with a minor change. jsonp_strucutre = "hello = ("+ json.dumps(arr) + ")" – jyotirmaya ojha Jun 02 '17 at 06:20