Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enforce the shape of a JSON/JSONB in Postgres?

I am trying to store the response to questions of a survey in JSON, as they could be in boolean(Is this Bar? Yes/No), number(How much is Foo?), string(Describe what is Foo). It is working fine, but how can I enforce that for a certain question, the JSON will be of identical shape?

For example, for the question "How many Foo or Bar do you eat everyday?", I am expecting the following structure(let's say it is column answer):

{
 "foo": "number",
 "bar": "number"
}

How can I enforce that and keep my data consistent?

like image 907
John Winston Avatar asked Dec 06 '25 17:12

John Winston


1 Answers

There 'right' way yo do this is either to normalize your data or to enforce schema at the application level.

Postgres JSON is delibrately schemaless. The idea is that if your data is structured it should probably be in normal columns. However, JSON is a totally valid option in the situation where the data is structured but the schema is dynamic. In those situations it's best to enforce schema constraints at the application layer.

like image 149
Nick Bailey Avatar answered Dec 08 '25 21:12

Nick Bailey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!