Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

JSON object format is verbose:

"[{"id":1,"name":"John"}, {"id":2,"name":"Jack"}]"

Sometimes, repeating field names take more space than the actual data. To save bandwidth, and speed up page loading, I would like to generate a JavaScript array of arrays in string format instead and send it to the client. For example for this data:

create table temp (
  id int,
  name text
);

insert into temp values (1, 'John'), (2, 'Jack');

I would like to get '[[1, "John"], [2, "Jack"]]'. How can I do that?

I do not want to aggregate columns by typing them out, since that would be hard to maintain. I also know postgresql does not allow multiple types in an array like JavaScript, so one possibility is to use composite types, but then, stringified/aggregated result ends up having '()' in them.

share|improve this question
up vote 1 down vote accepted
select array_to_json(array_agg(json_build_array(id, name)))
from temp;
       array_to_json       
---------------------------
 [[1, "John"],[2, "Jack"]]
share|improve this answer
    
This worked when replaced jsonb_build_array with json_build_array. Postgresql 9.4 triggered an error for the former. – mmatt 2 days ago
    
This is very close to what I wanted so I can go with it. I was actually after something like select array_to_json(array_agg(json_build_array(temp))) from temp; but that again converts rows to JSON object types. – mmatt 2 days ago
    
That is possible but it is another question. Ask it and I or someone else might answer it. – Clodoaldo Neto 2 days ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.