【问题标题】:How to handle the JSON formatted string?如何处理 JSON 格式的字符串?
【发布时间】:2013-11-25 11:06:49
【问题描述】:

我使用 json.dumps() 处理值并希望在前端显示它们。

我将标头设置为“application/json”,但效果不佳,在浏览器中将引用转换为"

如何将它们转换为正常输出,例如 {"key": "value"} 而不是 {"key": "value"}?

这是我的url。我使用 web.py 来处理数据。

import json
import os
import urllib2
import web

app_root = os.path.dirname(__file__)
templates_root = os.path.join(app_root, 'templates')
render = web.template.render(templates_root)

class Callback:
    def GET(self):
        web.header('Content-Type', 'application/json; charset=utf-8')
        url = "http://www.reddit.com/r/pics/hot.json"
        hdr = { 'User-Agent' : 'super happy flair bot by /u/spladug' }
        req = urllib2.Request(url, headers=hdr)
        html = urllib2.urlopen(req).read()
        html = json.dumps(html)  
        func_name = web.input()['callback']
        html = '{0}({1})'.format(func_name, html)
        return render.callback(html)

【问题讨论】:

  • 您使用的是什么网络框架?它可能会自动转义您的输出,您需要将其标记为“安全”。
  • 您的 Web 框架正在转义输出。你用的是什么框架?
  • @FogleBird 我使用 webpy。
  • @LieRyan 我使用 webpy。
  • 您使用的是模板吗?另外,请参见此处:stackoverflow.com/questions/3513446/webpy-how-to-serve-json

标签: python json web.py


【解决方案1】:

return render.callback(html) 更改为return html - 这里不需要模板引擎。

另外,您可以考虑使用 requests 模块而不是 urllib2。好多了。

【讨论】:

  • 谢谢,但引号现在有一个反斜杠前缀。
猜你喜欢
  • 2016-12-28
  • 1970-01-01
  • 2013-05-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-24
  • 2014-03-07
相关资源
最近更新 更多