Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/313.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从数据库查询输出创建JSON字符串_Python_Json_Python 3.x - Fatal编程技术网

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

Python 从数据库查询输出创建JSON字符串,python,json,python-3.x,Python,Json,Python 3.x,我尝试从数据库查询的输出中创建一个简单的JSON对象,该对象如下所示: json_obj= { '1': 'test_1', '2': 'test_2', '3': 'test_3', '4': 'test_4', '5': 'test_5', } 到目前为止,我一直在尝试循环和json.dump,但无法正确执行: cat_list = [] cats = Cat

我尝试从数据库查询的输出中创建一个简单的JSON对象,该对象如下所示:

json_obj= {
           '1': 'test_1',
           '2': 'test_2',
           '3': 'test_3',
           '4': 'test_4',
           '5': 'test_5',
           }
到目前为止,我一直在尝试循环和json.dump,但无法正确执行:

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()}
您需要一个
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()}

或者作为单行dict理解:
cat_dict={cat.id:cat.name for cat in Category.query.all()}
。或者作为单行dict理解:
cat_dict={cat.id:cat.name for cat in Category.query.all()}