U kunt een bulkinvoeging doen op basis van het json-document. U moet het document opnieuw formatteren omdat het formaat dat in de vraag wordt weergegeven vreemd en onpraktisch is.
Volledig werkend voorbeeld:
create table example(id int primary key, email text, last_name text, first_name text);
with jsondata(jdata) as (
values
(
'[
{"id": 1, "email": "[[email protected]]", "first_name": "John", "last_name": "Doe"},
{"id": 2, "email": "[[email protected]]", "first_name": "Robert", "last_name": "Duncan"},
{"id": 3, "email": "[[email protected]]", "first_name": "Ram", "last_name": "Das"},
{"id": 4, "email": "[[email protected]]", "first_name": "Albert", "last_name": "Pinto"},
{"id": 5, "email": "[[email protected]]", "first_name": "Robert", "last_name": "Peter"},
{"id": 6, "email": "[[email protected]]", "first_name": "Christian", "last_name": "Lint"},
{"id": 7, "email": "[[email protected]]", "first_name": "Mike", "last_name": "Hussey"},
{"id": 8, "email": "[[email protected]]", "first_name": "Ralph", "last_name": "Hunter"}
]'::jsonb)
)
insert into example
select (elem->>'id')::int, elem->>'email', elem->>'last_name', elem->>'first_name'
from jsondata,
jsonb_array_elements(jdata) as elem;
Het resultaat:
select *
from example
id | email | last_name | first_name
----+---------------+-----------+------------
1 | [[email protected]] | Doe | John
2 | [[email protected]] | Duncan | Robert
3 | [[email protected]] | Das | Ram
4 | [[email protected]] | Pinto | Albert
5 | [[email protected]] | Peter | Robert
6 | [[email protected]] | Lint | Christian
7 | [[email protected]] | Hussey | Mike
8 | [[email protected]] | Hunter | Ralph
(8 rows)
Als u de tabel wilt bijwerken (in plaats van erin in te voegen):
with jsondata(jdata) as (
-- values as above
)
update example set
email = elem->>'email',
last_name = elem->>'last_name',
first_name = elem->>'first_name'
from jsondata,
jsonb_array_elements(jdata) as elem
where id = (elem->>'id')::int;