【问题标题】:Reading and Writing from Json File using Python and Javascript使用 Python 和 Javascript 从 Json 文件中读取和写入
【发布时间】:2017-06-02 05:51:37
【问题描述】:

我应该读取一个 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 将对 js 进行 eval 并且不可用
  • @karthick 我怎样才能通过 javascript 读回我的 python 对象(已转换为 json)?
  • 您必须使用 ajax 请求调用您的 json

标签: javascript html json python-3.x


【解决方案1】:

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

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

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

【讨论】:

猜你喜欢
  • 2017-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-13
  • 1970-01-01
相关资源
最近更新 更多