Does PostgreSQL provide any notation / method for limiting the restriction on each element of the JSON array?
Example:
create table orders(data json);
insert into orders values ('
{
"order_id": 45,
"products": [
{
"product_id": 1,
"name": "Book"
},
{
"product_id": 2,
"name": "Painting"
}
]
}
');
I can easily add a field constraint order_id:
alter table orders add check ((data->>'order_id')::integer >= 1);
Now I need to do the same with product_id. I can set a restriction on individual elements of the array:
alter table orders add check ((data->'products'->0->>'product_id')::integer >= 1);
alter table orders add check ((data->'products'->1->>'product_id')::integer >= 1);
So it’s obvious that I'm looking for some kind of wildcard operator for that matches any element of the JSON array :
alter table orders add check ((data->'products'->*->>'product_id')::integer >= 1);
, , products orders. , JSON, .