← Back to PostgreSQL, page 2

postgresql-0033 · Medium mid

What does PostgreSQL print when the same document is stored as json and as jsonb?

json stores the input text exactly, keeping whitespace, key order and duplicate keys. jsonb stores a parsed binary form: whitespace is dropped, keys are sorted by length and then bytes, and only the last of duplicate keys survives. jsonb is slower to write but faster to query and can be indexed, so it is the default choice.

Full answer

Test data:

sql
CREATE TABLE docs (j json, jb jsonb);
INSERT INTO docs VALUES ('{"b": 1,  "a": 2, "a": 3, "long_key": [1, 2]}', '{"b": 1,  "a": 2, "a": 3, "long_key": [1, 2]}');
sql
SELECT j::text AS as_json, jb::text AS as_jsonb FROM docs;

Output:

text
                    as_json                    |               as_jsonb
-----------------------------------------------+--------------------------------------
 {"b": 1,  "a": 2, "a": 3, "long_key": [1, 2]} | {"a": 3, "b": 1, "long_key": [1, 2]}
(1 row)
sql
SELECT j->>'a' AS json_a, jb->>'a' AS jsonb_a, jb = '{"a": 3, "b": 1, "long_key": [1, 2]}'::jsonb AS jsonb_equal FROM docs;

PostgreSQL returns:

text
 json_a | jsonb_a | jsonb_equal
--------+---------+-------------
 3      | 3       | t
(1 row)
sql
SELECT j = j FROM docs;

Result on PostgreSQL 17:

text
ERROR:  operator does not exist: json = json

The json column returns the text unchanged, double space and duplicate key included, while jsonb shows a normalised document with one "a" whose value is 3. Looking up 'a' in json returns the last duplicate as well, but the stored text still has both, which can confuse other consumers. jsonb values compare by content regardless of key order. json has no equality operator at all, so comparing json values fails with 'could not identify an equality operator for type json'; this also blocks DISTINCT and GROUP BY on json columns.

sql
CREATE TABLE docs (j json, jb jsonb);
INSERT INTO docs VALUES ('{"b": 1,  "a": 2, "a": 3, "long_key": [1, 2]}', '{"b": 1,  "a": 2, "a": 3, "long_key": [1, 2]}');

SELECT j::text AS as_json, jb::text AS as_jsonb FROM docs;

SELECT j->>'a' AS json_a, jb->>'a' AS jsonb_a, jb = '{"a": 3, "b": 1, "long_key": [1, 2]}'::jsonb AS jsonb_equal FROM docs;

SELECT j = j FROM docs;

Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.

Key points

  • json keeps text exactly
  • jsonb normalises and deduplicates keys
  • jsonb compares by content
  • json has no equality operator
  • Prefer jsonb for querying and indexing

Common mistakes

  • Using json and then trying to GROUP BY it
  • Relying on key order in jsonb

Follow-ups

  • When is json the better choice?
  • How large can a jsonb value be?

Tips

  • Show the duplicate key