6

i'm having one table like

  name | age 
   abc | 20
   pqr | 30

I want result in json array like

{
 [{
   "name":"abc",
   "age":20 
 },
 {
  "name":"pqr",
   "age":30 
 }]
}

I know their is method

row_to_json();

that will be give me only single row of json but i want array, please help me on this

2 Answers 2

14
select json_agg(row_to_json(t))
from t
;
                      json_agg                      
----------------------------------------------------
 [{"name":"abc","age":20}, {"name":"pqr","age":30}]
Sign up to request clarification or add additional context in comments.

1 Comment

A detail, even if it's obvious (it wasn't for me at the first sight): t is the table name.
4

You can try:

SELECT array_to_json(array_agg(row_to_json(data)))
FROM (select name, age from your_table) data

You also can see more at this link:

https://hashrocket.com/blog/posts/faster-json-generation-with-postgresql

Hope it useful to you.

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.