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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With