Skip to main content
 首页 » 编程设计

python之从数据库查询输出创建 JSON 字符串

2025年05月04日25wayfarer

我尝试从数据库查询的输出创建一个简单的 JSON 对象,它看起来像这样:

json_obj= { 
           '1': 'test_1', 
           '2': 'test_2', 
           '3': 'test_3', 
           '4': 'test_4', 
           '5': 'test_5', 
           } 

到目前为止,我一直在尝试 for loops 和 json.dumps 但无法正确处理:

cat_list = [] 
cats = Category.query.all() 
for cat in cats: 
    item = { 
            cat.id: cat.name 
           } 
    cat_list.append(item) 
 
json_cat_list = json.dumps(cat_list) 

这确实创建了一个 JSON 对象,但不是我正在寻找的对象。

json_obj= { 
           {'1': 'test_1'}, 
           {'2': 'test_2'}, 
           {'3': 'test_3'}, 
           {'4': 'test_4'}, 
           {'5': 'test_5'}, 
           } 

关于如何做到这一点有什么建议吗?

非常感谢

请您参考如下方法:

您需要一个单个 dict 对象,而不是它们的列表。

cat_dict = {}                         # 1 
for cat in Category.query.all(): 
    cat_dict[cat.id] = cat.name       # 2 
 
json_cat_dict = json.dumps(cat_dict)  # 3 

或者,(正如下面提到的@Daniel Roseman)为了简洁起见,您可以将所有内容压缩到一个字典理解中:

cat_dict = {cat.id: cat.name for cat in Category.query.all()}