In my Postgres database I naively created a column in table Foos
as a json[]
that looks like this:
TABLE Foos
id | ... | baas
--------------------------------
1 | ... | [
| ... | {
| ... | "name": "a",
| ... | "property": "1",
| ... | },
| ... | {
| ... | "name": "b",
| ... | "property": "2",
| ... | },
| ... | ...
| ... | ]
2 | ... | [ ... ]
3 | ... | [ ... ]
Now I want to populate table Baas
with the items in my json array like this:
TABLE Baas
id | foo_id | name | property
------------------------------
1 | 1 | a | 1
2 | 1 | b | 2
How can I do this in simple SQL?
2
Answers
I solved it myself:
Use
json_populate_record()
orjson_populate_recordset()
.Short, casts to target types implicitly, and fast.
But get your setup and terminology straight!
json[]
is a Postgres array ofjson
. While this is totally possible, it’s unlikely. Once you work with JSON, you would typically nest a JSON array in the plain Postgres typejson
.Depending on what you have exactly, setup and solution are subtly different:
json[]
: Postgres array of json(Less likely.)
Setup
Wait, that syntax looks confusing! See:
Queries
One of these two:
json
: scalar type with nested JSON array(More likely.)
Setup
Query
fiddle