繁体   English   中英

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

[英]Reading and Writing from Json File using Python and Javascript

我应该阅读一个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”,“ There”],[“ Good”,“ Morning”,“!”]]

json对象已成功创建,但是我无法通过javascript函数将其读回。 我要去哪里错了? 我有一个约束,我不能去BeautifulSoup。 提前致谢。

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM