我在一個tornado應用的handler中從mongodb中讀到了一個集合的所有文檔,將轉換成了json格式,然后我用這些json數據為傳入了tornado模板中,顯示在了瀏覽器中。handler的代碼是樣的:class MainHandler(BaseHandler):
def get(self):
codes = self.db.code.find()
result = json.dumps(list(codes),
default=json_util.default,
sort_keys=True,
ensure_ascii=False,
indent=4)
print result
self.render('index.html', content = result)瀏覽器中顯示是這樣的:就是一個沒換行的狀態。在終端打印時,卻又是換了行的:記得在django中,可以使用content.linebreaks來換行換行之類的,在tornado中,卻沒找到這種方法。煩請幫助一下。
1 回答

一只斗牛犬
TA貢獻1784條經驗 獲得超2個贊
dumps
的時候,是不會加縮進之類的。你的dumps
指定了indent=4
。
indent
參數針對打印輸出時候的format
。
具體可以看文檔:
If indent is a non-negative integer (it is None by default), then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. None is the most compact representation.
還有一個比較好的工具,標準庫pprint
用來print
對象的時候顯示更美觀:
from?pprint?import?pprint pprint(your_obj)
- 1 回答
- 0 關注
- 1117 瀏覽
添加回答
舉報
0/150
提交
取消