将 Javascript 生成的 JSON 字符串保存为文件:web2py

Save a JSON String which is generated by Javascript as a file: web2py

[日志] {"image":"/SAS/default/download/uploads.image.85f2588e34848596.30362d32353033392e746966.tif","filename":"/SAS/default/download/06-25039.tif","start":1437444049436,"width":1080,"height":734,"events":[{"colour":"#0000ff","width":3, "erased":false,"points":[{"x":795,"y":256,"time":1437444050332},{"x":754, "y":260,"time":1437444050338},{"x":642,"y":271,"time":1437444050355},{"x": 466,"y":291,"time":1437444050372},{"x":268,"y":318,"time":1437444050389},{"x":148,"y":344,"time":1437444050406},{"x":101,"y":359,"time":1437444050423},{"x":92,"y":369,"time":1437444050441},{"x":104,"y":377,"time":1437444050458},{ "x":161,"y":381,"time":1437444050475},{"x":268,"y":381,"time":1437444050492} ,{"x":405,"y":366,"time":1437444050509},{"x":513,"y":346,"time": 1437444050527},{"x":557,"y":328,"time":1437444050544},{"x":554,"y":315,"time":1437444050562},{"x":529,"y":305,"time":1437444050579},{"x":484,"y":301,"time":1437444050596},{"x":435,"y":304,"time":1437444050613},{"x":4 01,"y":316,"time":1437444050630},{"x":388,"y":329,"time":1437444050648},{"x":389,"y":342,"time":1437444050665},{"x":406,"y":356,"time":1437444050682},{"x":430,"y":367,"time":1437444050699},{"x":449,"y":370,"time":1437444050716},{ "x":457,"y":370,"time":1437444050733},{"x":458,"y":370,"time":1437444050751} ,{"x":457,"y":368,"time":1437444050769}]}],"end":1437444051345,"elapsed":1909}(实验,线164)

这是我需要的字符串 save.I 必须执行两项任务:

  1. 将字符串保存在系统上并将其显示为视图(原样)

  2. 仅显示特定参数。比如"elapsed"这个字符串作为一个View.

我该怎么做? 谢谢您的帮助! :)

根据您要显示 JSON 字符串的 what/how,您有一些不同的选择。如果你想显示存储在变量 strJSON 中的原始 JSON 字符串,你可以使用 {{ =strJSON }} 将它注入视图中适当的位置。 web2py 有一个内置方法 BEAUTIFY,它使注入的变量输出看起来更好,即你可以调用 {{ =strJSON }} 来利用它。

如果您只想打印某些元素和/或自己手动格式化,如您的第二个问题,我建议将 JSON 字符串转换回 Python 对象。 web2py 有一个名为 SimpleJSON 的模块,它可以为您完成所有 JSON encoding/decoding 魔法。它位于 gluon.contrib.simplejson。要将 JSON 字符串转换为对象,您可以使用函数 'loads'。要将 Python 对象转换为 JSON 字符串,请使用 'dumps'。所以,例如:

{{ 将 gluon.contrib.simplejson 导入为 sjson }}

{{ myObj = sjson.loads(strJSON) }}

{{ strJSON = sjson.dumps(myObj) }}

现在您的 JSON 字符串已存储为对象,您可以像通常在 Python 中访问元素一样,具体取决于您的对象是列表、字典等。因此,对于例如,如果我们将您屏幕截图中的 JSON 转换为一个对象,我们可以像 Python:

中那样访问图像名称

imgname = myObj["image"]

同样,您可以通过以下方式访问第一个事件:

my_events = myObj["events"][0]

这是'colour'、'width'等的字典