0

Query result:

|  student_id  |  name  |  age  |  group  | 
---------------+--------+-------+----------  
| 1413001      | Ann    | 14    | Tennis  |
| 1413001      | Ann    | 14    | Choir   |

If I select records like this, I want to make them to JSON Object like

{student_id: "1413001", name: "Ann", Age: "14", group:["Tennis", "Choir"]}

How can I make them like that in Java or SQL?

1

1 Answer 1

1

demo: db<>fiddle

SELECT 
    row_to_json(s) 
FROM (
    SELECT 
        student_id, 
        name, 
        age, 
        json_agg("group") as "group"
    FROM students 
    GROUP BY student_id, name, age
) s
  1. Group the "groups" into a json array with json_agg
  2. The whole subquery rows can be converted into json objects with row_to_json

https://www.postgresql.org/docs/current/static/functions-json.html


Notice that "group" is a reserved word in Postgres. I recommend to rename this column.

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

Comments

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.