【问题标题】:jsonify/pretty-print JSON for Bottle用于瓶子的 jsonify/pretty-print JSON
【发布时间】:2016-03-05 21:47:50
【问题描述】:

我正在Bottle 中制作一个JSON 输出API,我想漂亮地打印JSON。现在如果我写return json.dumps(data, indent=4, default=json_util.default),它仍然会在我的浏览器中打印它而不使用缩进或换行符(但它确实可以正确打印到我的终端中)。

我的问题基本上是这个的瓶子版本: Flask Display Json in a Neat Way

但我不能使用答案,因为(据我所知)Bottle 中没有 jsonify 函数。有没有明显的解决方案,或者我应该尝试对 Flask 的jsonify 进行逆向工程?

【问题讨论】:

  • 您的浏览器默认将文本解释为 HTML,它不会打印 \n 并省略连续的空格。将您的 JSON 包装在 <pre> 或将 Content-Type 设置为 application/json
  • 是的,设置response.content_type 是这里的方法
  • 哇,伙计,我知道拖延手动设置内容类型是明显/不合适的。谢谢!如果有人迁移到答案,我会接受。

标签: python json bottle pretty-print


【解决方案1】:

感谢@Felk 评论: 将resopnse.content_type设置为application/json

def result():
    response.content_type='application/json'
    return data

def result():
    return '<pre>{}</pre>'.format(json.dumps(data, 
            indent=4, default=json_util.default))

两者都适合你。

【讨论】:

    【解决方案2】:

    我创建了 bottle-json-pretty 插件来扩展由 Bottle 完成的现有 JSON 转储。

    我喜欢能够在其他返回实际页面的模板/视图函数中使用我的 Bottle JSON/API 函数返回的字典。调用 json.dumps 或制作包装器会破坏这一点,因为它们会返回转储的 str 而不是 dict

    使用 bottle-json-pretty 的示例:

    from bottle import Bottle
    from bottle_json_pretty import JSONPrettyPlugin
    
    app = Bottle(autojson=False)
    app.install(JSONPrettyPlugin(indent=2, pretty_production=True))
    
    @app.get('/')
    def bottle_api_test():
        return {
            'status': 'ok',
            'code': 200,
            'messages': [],
            'result': {
                'test': {
                    'working': True
                }
            }
        }
    
    # You can now have pretty formatted JSON
    # and still use the dict in a template/view function
    
    # @app.get('/page')
    # @view('index')
    # def bottle_index():
    #     return bottle_api_test()
    
    app.run()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-25
      • 2015-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-17
      相关资源
      最近更新 更多