3

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?

Community
  • 1
  • 1
thefourtheye
  • 607
  • 1
  • 6
  • 19
  • 3
    Your browser propably interprets the text as HTML by default, which doesn't print `\n` and ommits consecutive spaces. Either wrap your JSON in `
    ` or set the Content-Type to `application/json`
    – Felk Dec 01 '15 at 20:27
  • 1
    Yep, setting `response.content_type` is the way to go here – Eric Dec 01 '15 at 20:30
  • Aww man, see I knew it was obvious / inappropriate to procrastinate on manually setting the content-type. Thanks! If someone migrates to an answer, I'll accept it. – thefourtheye Dec 01 '15 at 20:35

2 Answers2

1

Thanks @Felk comment: set resopnse.content_typeto 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.

Ali Nikneshan
  • 3,500
  • 27
  • 39
0

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()
jmcker
  • 387
  • 4
  • 18