Reputation: 607
I'm making a JSON-output API in Bottle, and I would like to pretty-print the 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).
My question is basically the Bottle version of this: 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. Is there an obvious solution, or should I try to reverse-engineer Flask's jsonify
?
Upvotes: 3
Views: 2827
Reputation: 479
I created the bottle-json-pretty plugin to extend the existing JSON dump done by Bottle.
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. Calling json.dumps
or making a wrapper broke this since they would return the dumped str
instead of a dict
.
Example using 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()
Upvotes: 0
Reputation: 3502
Thanks @Felk comment:
set resopnse.content_type
to 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.
Upvotes: 1