简体   繁体   中英

jsonify/pretty-print JSON for Bottle

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 ?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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