1

I am trying to create JSON output using Postgres.

I am close to the solution I think.

SELECT D.PROJECT_ID,
    D.M_NAME,
    D.M_ID,
    JSON_AGG(D.TASK) AS TASKS
FROM
    (SELECT MILESTONES.ID AS M_ID,
            MILESTONES.NAME AS M_NAME,
            MILESTONES.DUE_DATE,
            PROJECT_ID,
            TASK
        FROM MILESTONES_TABLE MILESTONES
        LEFT JOIN
            (SELECT JSONB_BUILD_OBJECT('name',
                                        ASSIGNMENTS.NAME,
                                        'instructions',
                                        INSTRUCTIONS,
                                        'id',
                                        ASSIGNMENTS.ID) AS TASK,
                    MILESTONE_ID
                FROM ASSIGNMENTS) AS F ON MILESTONE_ID = MILESTONES.ID
        WHERE MILESTONES.PROJECT_ID = 270 ) AS D
GROUP BY D.PROJECT_ID,
    D.M_NAME,
    D.M_ID

My output is close to the solution. Please see below. The only problem is that the empty array are presented with [null] instead of []. How can I do this. enter image description here

1 Answer 1

1

I found the solution.

I hope it helps others.

SELECT D.PROJECT_ID,
    D.M_NAME,
    D.M_ID,
     count(d),
     
    COALESCE(NULLIF(json_agg(TASK)::TEXT, '[null]'), '[]')::JSON
FROM
    (SELECT MILESTONES.ID AS M_ID,
            MILESTONES.NAME AS M_NAME,
            MILESTONES.DUE_DATE,
            PROJECT_ID,
            TASK
        FROM MILESTONES_TABLE MILESTONES
        LEFT JOIN
            (SELECT case when count(ASSIGNMENTS.ID) = 0 then '[]' else JSONB_BUILD_OBJECT('name',

                                                ASSIGNMENTS.NAME,
                                                'instructions',
                                                INSTRUCTIONS,
                                                'id',
                                                ASSIGNMENTS.ID) END AS TASK,
                    MILESTONE_ID
                FROM ASSIGNMENTS GROUP BY ASSIGNMENTS.ID) AS F ON MILESTONE_ID = MILESTONES.ID
        WHERE MILESTONES.PROJECT_ID = 270 ) AS D
GROUP BY D.PROJECT_ID,
    D.M_NAME,
    D.M_ID;
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.