使用Python和Javascript读取和写入Json文件

使用Python和Javascript读取和写入Json文件,javascript,html,json,python-3.x,Javascript,Html,Json,Python 3.x,我应该将一个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([]) ar

我应该将一个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')
导入webbrowser,json
f=open('World.html','w')
arr=[]]
arr[0]。追加('Hello')
arr[0]。追加('There')
arr.append([])
arr[1]。追加('Good')
arr[1]。追加('Morning')
arr[1]。追加(“!”)
message=''函数Hello(){alert(outputjson.arr);}这不起作用,您知道它是''
f、 写(信息)
将open('outputjson.json','w')作为f:
json.dump(arr,f)
f、 关闭()
webbrowser.open\u new\u选项卡('World.html')
Outputjson.json如下所示: [[“你好”,“你好”,“早上好”,“早上好”!“]]

json对象已成功创建,但我无法通过javascript函数读回它。我哪里做错了? 我有一个限制,我不能去美苏。
提前谢谢

您不能像这样简单地将json文件加载到浏览器中。一种方法是向json文件发出XHR请求并加载它。另一种方法是将
json
转换为
jsonp
结构

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

通过上述更改,您的
hello
javascript函数将被JSON调用。您可以选择存储JSON以供进一步访问/处理。

有错误消息吗?没有,我看不到任何警报消息。很明显,如果我硬编码的话,这个警告消息会起作用。你不能像这样加载json。json将被评估为js,而不会被评估available@karthick然后如何通过javascript读回我的python对象(已转换为json)?您必须使用ajax请求调用json请参考以下jsonp答案:嘿,谢谢您的建议,它只做了一点小改动。jsonp_structre=“hello=(“+json.dumps(arr)+”)