Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres return json with group

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
)
like image 425
nick Avatar asked Jul 18 '17 04:07

nick


People also ask

How do I query JSON data in PostgreSQL?

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.

What is -> in PostgreSQL?

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.

Can Jsonb be an array?

(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.)

What is Json_build_object in PostgreSQL?

Converts a comma-separated argument list to a JSON object. The argument list consists of alternating keys and values.


2 Answers

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

like image 70
a_horse_with_no_name Avatar answered Sep 20 '22 15:09

a_horse_with_no_name


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;
like image 22
nick Avatar answered Sep 20 '22 15:09

nick