0

For the following data tables and function in pg12

create table orders
(
  orderid integer, grandtotal numeric(10, 2)
)

create table odetails
(
  orderid integer, detailid integer, description text
)

create function jorder() returns json as
begin
 return query select od.orderid, od.grandtotal, ds.detailid, ds.description
 from orders od
 join odetails ds on od.orderid = ds.orderid;
end;

How do I get return data in a JSON hierarchy like below?

[{
    "orderid": 1,
    "grandtotal": 100.00,
    "details": [{
            "detailid": 11,
            "description": "pen"
        },
        {
            "detailid": 12,
            "description": "orange"
        }
    ]
}, {
    "orderid": 2,
    "grandtotal": 200.00,
    "details": [{
            "detailid": 21,
            "description": "book"
        },
        {
            "detailid": 22,
            "description": "coffee"
        },
        {
            "detailid": 23,
            "description": "tea"
        }
    ]
}]
1
  • You should fix your question: the code you provided has syntax errors. Commented Sep 14, 2021 at 6:31

1 Answer 1

1

You should look into json functions . You need json_build_object to form the objects and json_agg to aggregate them into json array:

CREATE FUNCTION jorder() 
RETURNS json 
LANGUAGE sql
AS $$
  SELECT 
    json_agg(orders.order)
  FROM (
    SELECT 
      json_build_object(
        'orderid', od.orderid, 
        'grandtotal', od.grandtotal, 
        'details', array_agg(
          json_build_object(
            'detailid', ds.detailid,
            'description', ds.description
          )
        )
      ) as order
    FROM 
      orders od
      JOIN odetails ds on od.orderid = ds.orderid
    GROUP BY 
      od.orderid, od.grandtotal
  ) as orders 
$$;

Example at db<>fiddle

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.