首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >JSON输出格式为Bottle、Python和MongoDB

JSON输出格式为Bottle、Python和MongoDB
EN

Stack Overflow用户
提问于 2015-09-30 05:10:16
回答 1查看 172关注 0票数 0

我正在运行Bottle和python来从MongoDB中提取数据。我的输出是JSON对象格式。

我曾经有过这样的经历

代码语言:javascript
复制
{u'product': u'mortgage', u'Total_Product': 146533}
{u'product': u'debt collection', u'Total_Product': 65639}

但是想要去掉'u‘,并得到以下格式:

代码语言:javascript
复制
'product':'mortgage', Total_Product: 146533
'product':'debt collection' 'Total_Product:65639

运行这段代码后,我看到一个空白屏幕,没有结果,也没有错误消息。有什么建议吗?

代码语言:javascript
复制
# find a single  with all aggregates 
choices = dict(
    aggr1 = db.complaints.aggregate([{"$group":{"_id":"$disputed", "Total_Disputed":{"$sum":1}}},{"$sort":{"Total_Disputed":-1}},{"$project":{"_id":0, "disputed":"$_id", "Total_Disputed":1}}]),
    aggr2 = db.complaints.aggregate([{"$group":{"_id":"$product", "Total_Product":{"$sum":1}}},{"$sort":{"Total_Product":-1}},{"$project":{"_id":0, "product":"$_id", "Total_Product":1}}]),
    aggr3 = db.complaints.aggregate([{"$group":{"_id":"$response", "Total_Response":{"$sum":1}}},{"$sort":{"Total_Response":-1}},{"$project":{"_id":0, "response":"$_id", "Total_Response":1}}]),
    aggr4 = db.complaints.aggregate([{"$group":{"_id":"$submitted", "Total_Submitted":{"$sum":1}}},{"$sort":{"Total_Submitted":-1}},{"$project":{"_id":0, "submitted":"$_id", "Total_Submitted":1}}]),
    aggr5 = db.complaints.aggregate([{"$group":{"_id":"$timely", "Total_Timely":{"$sum":1}}},{"$sort":{"Total_Timely":-1}},{"$project":{"_id":0, "Timely":"$_id", "Total_Timely":1}}])
)

def convert_keys_to_string(choices):
    """Recursively converts dictionary keys to strings."""
    if not isinstance(choices, dict):
        return choices
    return dict((str(k), convert_keys_to_string(v)) 
        for k, v in dictionary.items())
aggr1 = 'aggr1'
aggr2 = 'aggr2'
aggr3 = 'aggr3'
aggr4 = 'aggr4'
aggr5 = 'aggr5' 

    return bottle.template('analytics.tpl',  things1 = choices[aggr1], things2 = choices[aggr2], things3 = choices[aggr3], things4 = choices[aggr4], things5 = choices[aggr5])

bottle.debug(True)
bottle.run(host='localhost', port=8082)

tpl如下所示:

代码语言:javascript
复制
<!DOCTYPE html>
<html>
<head>
<title> @2015 </title>
</head>
<body>
<p>

</p>
<p>
<ul>
%for thing1 in things1:
<li>{{thing1}}</li>
%end
</ul></p>
<p>
<ul>
%for thing2 in things2:
<li>{{thing2}}</li>
%end
</ul></p>



</body>
</html>

最亲切的问候

EN

回答 1

Stack Overflow用户

发布于 2015-09-30 14:03:18

您正在模板{{thing1}}中使用到字典字符串的转换。

只需编写模板,根据需要设置字典条目的格式:

代码语言:javascript
复制
%for thing1 in things1:
<li>'product':'{thing1.product}', Total_Product: {{thing1.Total_Product}}</li>
%end

代码语言:javascript
复制
%for thing1 in things1:
<li>'product':'{thing1.product}' 'Total_Product:{{thing1.Total_Product}}</li>
%end

你的问题不清楚,你更喜欢哪一个。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32853817

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档