2

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.

1 Answer 1

1
select array_to_json(array_agg(json_build_array(id, name)))
from temp;
       array_to_json       
---------------------------
 [[1, "John"],[2, "Jack"]]
3
  • This worked when replaced jsonb_build_array with json_build_array. Postgresql 9.4 triggered an error for the former. Commented Feb 24, 2016 at 15:14
  • 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. Commented Feb 24, 2016 at 16:04
  • That is possible but it is another question. Ask it and I or someone else might answer it. Commented Feb 24, 2016 at 17:35

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.