11

I am trying to create nested json array using 2 tables.

I have 2 tables journal and journaldetail.

Schema is -

journal : journalid, totalamount

journaldetail : journaldetailid, journalidfk, account, amount

Relation between journal and journaldetail is one-to-many.

I want the output in following format :

{  journalid : 1,
totalamount : 1000,
journaldetails : [ 
   {
      journaldetailid : j1,
      account : "abc",
      amount : 500 
   },
   {
      journaldetailid : j2,
      account : "def",
      amount : 500 
   }
]}

However, by writing this query as per this post the query is:

select j.*, row_to_json(jd) as journal from journal j
inner join (
  select * from journaldetail
) jd on jd.sjournalidfk = j.sjournalid

and the output is like this :

{  journalid : 1,
totalamount : 1000,
journaldetails : 
   {
      journaldetailid : j1,
      account : "abc",
      amount : 500 
   }
}
{  journalid : 1,
totalamount : 1000,
journaldetails : 
   {
      journaldetailid : j2,
      account : "def",
      amount : 500 
   }
}

I want the child table data as nested array in the parent.

1 Answer 1

21

I found the answer from here:

Here is the query :

select row_to_json(t)
from (
  select sjournalid,
    (
      select array_to_json(array_agg(row_to_json(jd)))
      from (
        select sjournaldetailid, saccountidfk
        from btjournaldetail
        where j.sjournalid = sjournalidfk        
      ) jd
    ) as journaldetail
  from btjournal j
) as t

This gives output in array format.

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

1 Comment

I this is still the best method with PostgreSQL 12+?

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.