How to constrain a JSONB field in Postgres

In Postgres, JSONB fields are very useful for storing semi-structured data. But sometimes the flexibility it offers can be a little bit scary. Imagine you want to store the result of some sort of inspection, which can lead to 2 different outputs, “create” or “update”. Along with other logs. You expect your JSON field values to look like this: { "action": "create", "some_useful_log_info": ... } or { "action": "update", "reason": ....

December 1, 2023 · 2 min · Francis Chabouis