0

The result I got from SQLite in Python looks like this:

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

I want to convert the result into JSON format like this:

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

I used GROUP_CONCAT to concat all the students' name and the following code:

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?

2 Answers 2

1

If your version of sqlite has the JSON1 extension enabled, it's easy to do in pure SQL:

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

DB Fiddle example

Sign up to request clarification or add additional context in comments.

Comments

0

You could just do result["Students"] = result["Students"].split(", ").

1 Comment

Nice! But what if the student's name contains ',' in it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.