JSON storage and validation
Overview
JSON represents objects, arrays and scalar values. Keep stable identifiers, prices and relationships in relational columns; use JSON for variable product attributes when the shape genuinely varies. PostgreSQL json preserves input text, while jsonb stores a processed representation. SQLite 3.46.1 supports text JSON and its own incompatible binary JSONB format.
First example
SELECT json_valid('{"a":1}'),json_valid('{a:1}'),json_type('[1,2]');Observed SQLite result (rows in JSON):
[ [ 1, 0, "array" ]]How it works
The fixture requires an object, an integer nonnegative price, a text category and an array of tags. json_valid checks syntax, not the business schema. CHECK rejects false but accepts SQL NULL, so use IS or COALESCE to reject missing required paths. A valid array is not a valid catalog object. The first example contrasts valid and invalid text; the second inspects SQLite binary storage without relying on its internal bytes. PostgreSQL jsonb drops duplicate object keys (last value wins); validate duplicates upstream when their presence matters. Do not store binary JSONB as an interchange format.
Practical example
SELECT typeof(jsonb('{"a":1}')),json_extract(jsonb('{"a":1}'),'$.a'),json_valid(jsonb('{"a":1}'),8);Observed SQLite result (rows in JSON):
[ [ "blob", 1, 1 ]]Practice and mistakes
Practice: try inserting an object without price in a fresh fixture. Hint 1: syntactic validation succeeds. Hint 2: the required-type CHECK rejects it. Then consider whether price should be a relational column in a real schema.
PostgreSQL 17 example — NOT RUN
SELECT json_typeof('{"a":1}'::json), jsonb_typeof('{"a":1}'::jsonb);Expected result, not executed: [["object", "object"]]