1

Stuck in one exercise task where I want JSON objects to be in form of a JSON array. Actually I have reached up to 1st stage to convert things into JSON object first.

Second stage is where my output should be as same as expected output as below, but it is not coming.

Current output :

{"name": "Peter", "uniqueId": "1"}
{"name": "MaryChan", "uniqueId": "3"}

Expected output :

[{"name": "Peter", "uniqueId": "1"}, {"name": "MaryChan", "uniqueId": "3"}]

Query :

SELECT JSON_OBJECT('uniqueId', uniqueId, 'name', name) actors
FROM (
select stf.id as familyId, stl.skill_type_name  as name
from actor_family af, actor_layered al
where af.id = al.actor_family_id) AS actors
GROUP BY uniqueId;

Some have suggested to use GROUP_CONCAT to get it done but still I'm not able to achieve the expected format.

Any help or pointers are welcomed.

1 Answer 1

3

You can use MySQL JSON_ARRAYAGG aggregation function:

SELECT JSON_ARRAY_AGG(JSON_OBJECT('uniqueId', uniqueId, 'name', name)) actors
FROM (
select stf.id as familyId, stl.skill_type_name  as name
from actor_family af, actor_layered al
where af.id = al.actor_family_id) AS actors
GROUP BY uniqueId;

Try it here.

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

3 Comments

Man, that's simplest and elegant approach i have learned today. Big thanks again for giving me helping hand.
Additional small tip: as long as this is an aggregation function, you can use a GROUP BY clause if you need to group specific rows that belong together on other columns. Glad this answer was helpful for you. @THINKINGMACHINE
Aye cap. Noted.

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.