使用Python和JavaScript从JSON文件读取和写作



我应该读取一个python数据结构,这是一个2D列表,可以精确地列入JavaScript函数。我知道这可以在将Python数据结构转换为JSON对象后,然后使用JavaScript函数读取JSON对象后可以完成。我正在使用Python脚本渲染HTML页面,如下所示。

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看起来像这样:[[" hello"," were"],["好","早晨","!"]

JSON对象是成功创建的,但我无法通过我的JavaScript函数读取它。我要去哪里?我有一个约束,我不能去美丽的小组。提前致谢。

您无法将JSON文件简单地加载到浏览器中。一种方法是向JSON文件提出XHR请求并加载它。另一种方法是将您的json转换为jsonp结构。

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

随着上述更改,您的hello JavaScript功能将使用JSON调用。您可以选择存储JSON以进行进一步访问/处理。

最新更新