0

Here is a table:

create table test(
  fjson jsonb
);

then insert some value:

insert into test values
('{"name":"A"}'::jsonb),
('{"name":"B"}'::jsonb),
('{"name":"C"}'::jsonb);

I want to get a json array like below:

[
  {"name":"A"},
  {"name":"B"},
  {"name":"C"}
]

How to write the SQL?

Thanks.

Problem solved. thanks

do $$ declare
    jdata jsonb;
begin
    create temp table test(
      fjson jsonb
    ) on commit drop;
    
    insert into test values
    ('{"name":"A"}'::jsonb),
    ('{"name":"B"}'::jsonb),
    ('{"name":"C"}'::jsonb);
    
    select (select jsonb_agg(fjson) from test) into jdata;
    raise notice '%',jdata;
end;
$$ language plpgsql;

1 Answer 1

1

You can use

SELECT jsonb_agg(fjson) from test

to get a jsonb array, or

SELECT array_agg(fjson) from test

to get a native pg array.

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.