1

postgesql returns the json_build_object as a parent for each grouped json array like this:

 {
  "stories": [{
        "json_build_object": {
          "CNN": []
        }
      },
      {
        "json_build_object": {
          "FOX": []
        }
      },
      {
        "json_build_object": {
          "Huffpost": []
        }
      },...

Postgresql returns the "json_build_object" as a key. Is it possible to replace with the stories.source value returned by the group by? Tried an ALIAS but that returned an error.

SELECT json_build_object(source, json_agg(stories.*))
FROM stories
GROUP BY stories.source
ORDER BY source;

Optimal solution would be a response like this:

 stories:
  CNN: [],
  FOX: []...

I'm sure I'm missing a best practice for returning JSON in Postgresql...

3
  • 2
    SELECT json_object_agg(source, strs) FROM (SELECT source, array_agg(stories.*) as strs FROM stories GROUP BY stories.source ORDER BY source) as t;? Commented Jul 25, 2017 at 18:57
  • Definitely better than my query. Thanks Commented Jul 27, 2017 at 14:47
  • Thanks @Abelisto ! would upvote if you post it as an answer. Commented Jan 13, 2020 at 23:42

1 Answer 1

1

Use json_agg before json_object_agg like this.

select test json_agg(json_oject_agg(...)) test;
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.