简体   繁体   English

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

[英]Convert sql query result into JSON array in python

The result I got from SQLite in Python looks like this:我从 Python 中的 SQLite 得到的结果如下所示:

{"John", "Alice"}, {"John", "Bob"}, {"Jogn", "Cook"} ......

I want to convert the result into JSON format like this:我想将结果转换为 JSON 格式,如下所示:

{
    "Teacher": "John",
    "Students": ["Alice", "Bob", "Cook" .....]
}

I used GROUP_CONCAT to concat all the students' name and the following code:我使用 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)))

I was able to get this result:我能够得到这个结果:

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

How can I make the students into array format?我怎样才能让学生变成数组格式?

If your version of sqlite has the JSON1 extension enabled, it's easy to do in pure SQL:如果您的 sqlite 版本启用了JSON1扩展,那么在纯 SQL 中很容易做到:

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

DB Fiddle example DB Fiddle 示例

You could just do result["Students"] = result["Students"].split(", ") .你可以做result["Students"] = result["Students"].split(", ")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM