为Bottle格式化JSON并进行漂亮打印

3
我正在使用Bottle制作一个JSON输出API,并且我想将JSON格式化输出。目前,如果我写return json.dumps(data, indent=4, default=json_util.default),它仍然会在我的浏览器中打印出没有缩进或换行的内容(但它在我的终端中正确打印)。我的问题基本上就是这个Bottle版本: Flask Display Json in a Neat Way,但是我无法使用该答案,因为(据我所知)Bottle中没有jsonify函数。是否有明显的解决方案,或者我应该尝试反向工程Flask的jsonify函数?

3
您的浏览器可能默认将文本解释为HTML,这会忽略\n并省略连续的空格。要么将您的JSON包装在<pre>标签中,要么将Content-Type设置为application/json - Felk
1
没错,在这里设置 response.content_type 是正确的做法。 - Eric
啊,我知道拖延手动设置内容类型是明显的/不恰当的。谢谢!如果有人迁移到一个答案,我会接受它。 - thefourtheye
2个回答

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))

两者都适合你。


0

我创建了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()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接