I have a table like this:
orders order_number products 1234 [{"upc":2434354, "title":"Widget"}] 4321 [{"upc":6434556, "title":"Shorts"}, {"upc":54346, title: "Shirt"}]
I want to generate an output like this
[ {order_number: 1234, upc: 2434354}, {order_number: 4321, upc: 6434556} ]
As you can see I pull out the UPC from the array (targeting the first element in the array only).
Note that products
if of type jsonb
I tried this:
SELECT jsonb_array_elements(products)[0]->>upc FROM orders ORDER BY created DESC LIMIT 10
But it gives a syntax error, I’m not sure exactly how to do array traversal in PostgreSQL
Also there is the possibility that products
may be an empty array []
Advertisement
Answer
SELECT jsonb_agg( jsonb_build_object( 'order_number', order_number, 'upc', products -> 0 -> 'upc' ) ) FROM orders
products -> 0 -> 'upc'
gets theupc
value of the first array elementjsonb_build_object()
builds one JSON object per record containing theorder_number
andupc
valuejsonb_agg()
aggregates these JSON objects into one JSON array