Python / Flask BSON问题,如何遍历键和值?

时间:2019-03-25 09:58:28

标签: python json mongodb flask bson

我正在尝试以简单明了的方式从对象获取键和值,并使用flask-session库存储它们,但是看起来该对象是MongoDB的BSON,并且无法像JSON对象那样工作工作。

什么已经起作用:

single_recipe = mongo.db.recipes.find_one({'_id': ObjectId(single_id)})
session['single_id'] = single_id
creator = list(single_recipe.values())[1]
session['creator'] = creator
name = list(single_recipe.values())[2]
session['name'] = name
image = list(single_recipe.values())[3]
session['image'] = image
description = list(single_recipe.values())[4]
session['description'] = description
key_1 = list(single_recipe.values())[5]
session['key_1'] = key_1
calories = list(single_recipe.values())[6]
session['calories'] = calories
time = list(single_recipe.values())[7]
session['time'] = time
serves = list(single_recipe.values())[8]
session['serves'] = serves
sub_1 = list(single_recipe.values())[9]
session['sub_1'] = sub_1
voted_up = list(single_recipe.values())[10]
session['voted_up'] =  voted_up
voted_down = list(single_recipe.values())[11]
session['voted_down'] =  voted_down
upvotes = list(single_recipe.values())[12]
session['upvotes'] = upvotes
downvotes = list(single_recipe.values())[13]
session['downvotes'] = downvotes

什么不起作用:

single_recipe = mongo.db.recipes.find_one({'_id': ObjectId(single_id)})
session['single_id'] = single_id
for key, value in single_recipe.items():
    session[key] = value

当我尝试第二个选项时,出现此错误:

TypeError: Object of type ObjectId is not JSON serializable

我认为引起问题的项目是第一个条目:

'_id': ObjectId('5c6b439899e7e318893a9373')

打印时整个数据库条目如下:

  {'_id': ObjectId('5c6b439899e7e318893a9373'), 'creator': 'michael', 'name': 'miso ramen soup with buckwheat noodles', 'image': 'https://ichef.bbci.co.uk/food/ic/food_16x9_832/recipes/miso_ramen_soup_with_15548_16x9.jpg', 'description': 'This comforting, gluten-free broth is packed with fresh vegetables, while the miso paste brings great depth of flavour. Making your own bone broth adds extra goodness. ', 'key_ingredient_1': 'chicken', 'calories': '1832', 'time': '120', 'serves': '4', 'substitute_1': '', 'voted_up': 'michael', 'voted_down': 'lolasuser', 'upvotes': '1', 'downvotes': '2'}

可以帮忙吗?

0 个答案:

没有答案