Attempting to get a JSON response that is structured like this:
{
'news_source_1' : [{'headline': 'title'},{'headline': 'title'}],
'news_source_2' : [{'headline': 'title'},{'headline': 'title'}],
'news_source_3' : [{'headline': 'title'},{'headline': 'title'}]
}
The query calls a single table grouped by the news_source which is a column in the table.
My code groups by the news source but does not use the news source as a key:
SELECT array_to_json(array_agg(stories)) FROM stories GROUP BY source
Returns:
{
[{'headline': 'title'},{'headline': 'title'}],
[{'headline': 'title'},{'headline': 'title'}],
[{'headline': 'title'},{'headline': 'title'}]
}
Is it possible to use the news source column as the parent key? Not sure how to write this SQL query with the PG son syntax.
table
stories (
news_source,
headline
)
Querying the JSON documentPostgreSQL has two native operators -> and ->> to query JSON documents. The first operator -> returns a JSON object, while the operator ->> returns text. These operators work on both JSON as well as JSONB columns. There are additional operators available for JSONB columns.
PostgreSQL provides two native operators -> and ->> to help you query JSON data. The operator -> returns JSON object field as JSON. The operator ->> returns JSON object field as text.
(Note: It is possible to make a jsonb[] column, but we don't recommend it, as there's no value over a jsonb column that contains an array.)
Converts a comma-separated argument list to a JSON object. The argument list consists of alternating keys and values.
Don't aggregate the complete row, only the headline:
SELECT json_build_object(news_source, json_agg(headline))
FROM stories
GROUP BY news_source
ORDER BY news_source;
Online example: http://rextester.com/LUOUR61576
Thank you!
I slightly modified your working code to return a set of records per each group by instead of just a single field.
SELECT json_build_object(source, json_agg(stories.*))
FROM stories
GROUP BY source
ORDER BY source;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With