Difference between JSON and JSONB in PostgreSQL
What Happens When Storing JSON
When you insert text into a column of type JSON, PostgreSQL performs the following steps:
-
Syntax Validation (Minimal Parsing)
The most crucial step is validating the syntax. PostgreSQL must confirm that the input string is a well-formed JSON document according to the JSON standard (RFC 7159). This involves checking for things like:
- Matching brackets (
{}and[]). - Correct placement of colons (
:) and commas (,). - Properly quoted keys and strings.
- Valid JSON primitive types (numbers, booleans,
null).
If this check fails, the insertion will be rejected. This minimal parsing is necessary to ensure the column actually contains JSON, not just arbitrary text.
- Matching brackets (
-
Storage as Exact Text
After validation, the key characteristic of
JSONstorage kicks in: the exact input text is stored verbatim.- NO canonicalization of data structure.
- NO removal of whitespace.
- NO reordering of keys.
- NO removal of duplicate keys.
The stored value is simply a string of characters.
What Happens When Storing JSON
Below transformations are done when storing data in JSONB type
- canonicalization of data structure.
- removal of whitespace.
- reordering of keys.
- removal of duplicate keys.
Comparison of Transformations on Write
| Feature | JSON (Text Storage) | JSONB (Binary Storage) |
|---|---|---|
| Validation | Minimal: Only checks syntax compliance. | Full: Checks syntax and semantic properties (e.g., number range, valid Unicode). |
| Whitespace | Preserved (stored as-is). | Removed (stripped during parsing). |
| Key Order | Preserved (stored as-is). | Canonicalized (may be sorted/reordered). |
| Duplicate Keys | Preserved (stored as-is). | Eliminated (only the last value is kept). |
| Data Type Mapping | None (values remain as part of the text string). | Performed (values are mapped to native PostgreSQL types like int, text, etc.). |
Published on: Sep 30, 2025, 07:44 AM