简体   繁体   English

用于 Bottle 的 jsonify/pretty-print JSON

[英]jsonify/pretty-print JSON for Bottle

I'm making a JSON-output API in Bottle, and I would like to pretty-print the JSON.我正在 Bottle 中制作一个 JSON 输出 API,我想漂亮地打印 JSON。 Right now if I write return json.dumps(data, indent=4, default=json_util.default) , it still prints it without indents or newlines into my browser (but it does print correctly into my terminal).现在,如果我写return json.dumps(data, indent=4, default=json_util.default) ,它仍然在我的浏览器中打印它而不使用缩进或换行符(但它确实正确打印到我的终端中)。

My question is basically the Bottle version of this: Flask Display Json in a Neat Way我的问题基本上是这个的 Bottle 版本: Flask Display Json in a Neat Way

But I can't use the answer because (as far as I can tell) there is no jsonify function in Bottle.但我不能使用答案,因为(据我所知)Bottle 中没有jsonify函数。 Is there an obvious solution, or should I try to reverse-engineer Flask's jsonify ?是否有明显的解决方案,或者我应该尝试对 Flask 的jsonify进行逆向工程?

Thanks @Felk comment: set resopnse.content_type to application/json .谢谢@Felk 评论:将resopnse.content_type设置为application/json

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

or或者

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

both will work for you.两者都适合你。

I created the bottle-json-pretty plugin to extend the existing JSON dump done by Bottle.我创建了 Bottle -json-pretty插件来扩展 Bottle 完成的现有 JSON 转储。

I like being able to use the dictionary returned by my Bottle JSON/API functions in other template/view functions that return an actual page.我喜欢能够在返回实际页面的其他模板/视图函数中使用 Bottle JSON/API 函数返回的字典。 Calling json.dumps or making a wrapper broke this since they would return the dumped str instead of a dict .调用json.dumps或制作包装器会破坏这一点,因为它们会返回转储的str而不是dict

Example using bottle-json-pretty:使用 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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM