0

我正在使用 Shodan API,在将收到的 JSON 传递给模板(django)时遇到问题。

这是原始 JSON 结构:

{"matches": [{"city": "Montreal", "updated": "02.02.2013", "ip": "24.48.3.143", "longitude": -73.5833, "data": "HTTP/1.0 200 OK\r\nDate: Sat, 02 Feb 2013 00:41:53 GMT\r\nServer: Apache/1.3.42 (Unix) mod_auth_pam/1.1.1 DAV/1.0.3 mod_ssl/2.8.31 OpenSSL/0.9.8g\r\nSet-Cookie: iomega=174.79.246.153.26931359765713476; path=/\r\nCache-Control: no-cache\r\nConnection: close\r\nTransfer-Encoding: chunked\r\nContent-Type: text/html; charset=utf-8\r\n\r\n", "country_name": "Canada", "hostnames": [], "country_code": "CA", "country": "DEPRECATED: use country_name", "latitude": 45.5, "os": "Linux 2.6.x", "port": 443}]}

这是我传递给模板的数据结构:

[{"city": "Montreal", "updated": "02.02.2013", "os": "Linux 2.6.x", "ip": "24.48.3.143", "longitude": -73.5833, "latitude": 45.5, "hostnames": [], "country_code": "CA", "country": "DEPRECATED: use country_name", "country_name": "Canada", "data": "HTTP/1.0 200 OK\r\nDate: Sat, 02 Feb 2013 00:41:53 GMT\r\nServer: Apache/1.3.42 (Unix) mod_auth_pam/1.1.1 DAV/1.0.3 mod_ssl/2.8.31 OpenSSL/0.9.8g\r\nSet-Cookie: iomega=174.79.246.153.26931359765713476; path=/\r\nCache-Control: no-cache\r\nConnection: close\r\nTransfer-Encoding: chunked\r\nContent-Type: text/html; charset=utf-8\r\n\r\n", "port": 443}]

正如你所看到的,它里面有很多特殊的字符,这会扰乱转换。另一个问题是“主机名”子元素,它是元素列表(如果存在元素)......

任何人都知道如何以正确的格式处理 js/jquery 中的这个 JSON 文件?问候。

编辑:我正在检查我的 javascript 的输出,并且从 django 视图传递到模板的特殊字符被转换为 html 代码和 \r\n 消失导致解析错误:

我比较了这两个 json 文件:http: //json.parser.online.fr/

并且从 shodan api 接收并在视图中操作的 json 工作正常,但不是传递到模板的 JSON。

4

1 回答 1

0

我发现了问题,正如我在问题中所说,当我将 JSON 从视图传递到模板时,django 会转换 JavaScript 字符串中使用的字符。

解决方案是将 escapejs 标记添加到模板中的变量中:

{{ JSON|escapejs}}

在这里您可以找到文档:https ://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#escapejs

于 2013-02-07T18:44:31.973 回答