在python中将sql查询结果转换为JSON数组

在python中将sql查询结果转换为JSON数组,python,arrays,json,sqlite,Python,Arrays,Json,Sqlite,我在Python中从SQLite获得的结果如下: {"John", "Alice"}, {"John", "Bob"}, {"Jogn", "Cook"} ...... { "Teacher": "John", "Students": ["Alice", "Bob", "Cook" .....] } 我想将结果转换为JSON格式,如下所示: {"John", "Alice"}, {"John", "Bob"}, {"Jogn", "Cook"} ...... { "

我在Python中从SQLite获得的结果如下:

{"John", "Alice"}, {"John", "Bob"}, {"Jogn", "Cook"} ......
{
    "Teacher": "John",
    "Students": ["Alice", "Bob", "Cook" .....]
}
我想将结果转换为JSON格式,如下所示:

{"John", "Alice"}, {"John", "Bob"}, {"Jogn", "Cook"} ......
{
    "Teacher": "John",
    "Students": ["Alice", "Bob", "Cook" .....]
}
我使用GROUP_CONCAT记录所有学生的姓名和以下代码:

row_headers = [x[0] for x in cursor.description] #this will extract row headers
result = []
for res in cursor.fetchall():
    result.append(dict(zip(row_headers, res)))
我能够得到这个结果:

{
    "Teacher": "John",
    "Students": "Alice, Bob, Cook" 
}

如何将学生转换为数组格式?

您只需执行
result[“students”]=result[“students”]。拆分(“,”)

如果您的sqlite版本启用了扩展,那么在纯SQL中很容易做到:

SELECT json_object('Teacher', teacher,
                   'Students', json_group_array(student)) AS result
FROM ex
GROUP BY teacher;

不错!但是如果学生的名字中包含“,”怎么办?