2

When I execute

SELECT array_to_json(array_agg(row_to_json(curriculum_overview))) 
FROM study.curriculum_overview;

On a predefined view I have I get something similar to this

[{"study_programme":"SE","semester":1,"module_code":"B1"},...}]

I want this array wrapped in an object, and possibly add some metadata like a timestamp to it, example:

{
    timeStamp: now,
    data: [{...},{...},{...}]
}

How is this possible using a query? Or do I have to do this in a client and modify the data after obtaining the query results?

2
  • please elaborate Commented Sep 28, 2017 at 11:54
  • I want to wrap the JSON Array that Postgres gives me in a JSON Object using a query. Similar to this stackoverflow.com/questions/46231422/… Commented Sep 28, 2017 at 12:11

1 Answer 1

4

Use the function json_build_object(), e.g.:

SELECT 
    json_build_object(
        'timestamp', now(), 
        'metadata', 'some_value',
        'data', array_to_json(array_agg(row_to_json(co))))
FROM study.curriculum_overview co;
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.