Sub topic 2
Storing JSON in a table and writing JSON literals
This chapter covers how to add a JSON column to a table, how to write JSON values inside SQL statements, and what PostgreSQL does with those values when it stores them. It assumes you can write basic SQL (SELECT, INSERT, UPDATE, WHERE, JOIN), know JSON syntax, and can run CREATE TABLE on a PostgreSQL instance (version 12 or later). It also assumes you read the previous chapter and know that jsonb is the right default for most columns. All examples use jsonb.
Declaring a JSON column
A JSON column is an ordinary column with the type jsonb. The table below holds one row per order. The customer name is a normal column, and the variable parts of the order live in a document.
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer text NOT NULL,
details jsonb NOT NULL
);
INSERT INTO orders (customer, details) VALUES
('Ada', '{"status": "paid", "total": 42.50, "items": [{"sku": "A1", "qty": 2}, {"sku": "B7", "qty": 1}], "shipping": {"city": "Oslo"}}'),
('Grace', '{"status": "pending", "total": 10.00, "items": [{"sku": "A1", "qty": 1}], "shipping": {"city": "Bergen"}}');The later chapters in this tutorial query this table, so keep it.
Some points about the declaration:
NOT NULLis a choice. It forces every row to have a document. Without it, a row can hold SQLNULL, which is different from a JSONnull(covered below).- A
jsonbcolumn has no schema. PostgreSQL checks only that the value is valid JSON. The shape of each document is up to you, unless you add constraints, which a later chapter covers. - You can give the column a default, such as
details jsonb NOT NULL DEFAULT '{}'. The literal'{}'is an empty JSON object, so rows inserted without a value still get a valid document.
What an insert does
When you insert text into a jsonb column, PostgreSQL parses it, rejects it if it is not valid JSON, and converts it to an internal binary form. The original text is not kept. The diagram shows the path.
The conversion step explains several behaviors that surprise people the first time.
Normalization
The stored value can look different from the text you wrote:
SELECT '{"b": 1, "aa": 2, "a": 3, "a": 4}'::jsonb AS doc;The result is:
{"a": 4, "b": 1, "aa": 2}Three things happened:
- Extra whitespace was dropped. Output always has one space after each colon and comma.
- The duplicate key
"a"kept only its last value, 4. - The keys were reordered.
jsonbsorts keys by length first, then by bytes. Do not depend on any key order.
The json type keeps your text exactly as written, including whitespace, order, and duplicate keys. It still checks that the text is valid JSON on input. Use json only when you must preserve the original text.
Numbers
jsonb stores JSON numbers as PostgreSQL numeric. That means values keep their precision and trailing zeros, with no floating-point rounding:
SELECT '{"total": 42.50, "big": 12345678901234567890.123, "exp": 1e2}'::jsonb;The output is {"big": 12345678901234567890.123, "exp": 100, "total": 42.50}. The value 42.50 keeps its trailing zero, and 1e2 is printed as 100. Be aware that a client library may parse the JSON back into a floating-point number, and then the precision is gone. The database is not the cause of that loss.
Writing JSON literals
A JSON literal in SQL is a string with a type attached. You have to satisfy two syntaxes at once: SQL string rules on the outside and JSON rules on the inside.
The basic form
SELECT '{"name": "Ada", "tags": ["admin", "ops"], "active": true}'::jsonb;- The outer single quotes belong to SQL.
- The inner double quotes belong to JSON. JSON requires double quotes around every key and every string. Single quotes inside the document are not valid JSON.
::jsonbcasts the string to the type. You can write the same thing asCAST('...' AS jsonb).
In an INSERT ... VALUES into a jsonb column, the cast is optional. PostgreSQL treats an untyped string literal as the column's type. The cast becomes required when the literal has no target type, as in a bare SELECT, or when you pass the value as a typed parameter. Writing the cast is a good habit, because it makes the intent visible.
Apostrophes and quoting
A single quote inside a SQL string must be doubled. A document with the text it's fine looks like this:
SELECT '{"note": "it''s fine"}'::jsonb;This gets hard to read as documents grow. Dollar quoting avoids the problem. Between a pair of $$ markers, a single quote needs no escape:
SELECT $$ {"note": "it's fine", "path": "C:\\temp"} $$::jsonb;If your document might itself contain $$, give the delimiter a tag, such as $json$ ... $json$.
Backslashes need care. With the default setting standard_conforming_strings = on, SQL passes backslashes through unchanged, so the JSON parser sees them and applies JSON escape rules. To store one backslash in a JSON string, write \\ in the literal, as the example above does. Escapes such as \n, \", and \u00e9 are handled by the JSON parser:
SELECT '{"msg": "line1\nline2", "quote": "say \"hi\"", "e": "\u00e9"}'::jsonb;The \u00e9 escape turns into the character é when the value is parsed. The one exception is \u0000. jsonb rejects it with an error, because PostgreSQL text cannot contain a NUL character.
Comparing the quoting options
| Situation | Write | Result |
|---|---|---|
| Plain document | `'{"a": 1}'` | Works |
| Apostrophe in a value | `'{"a": "it''s"}'` | Double the single quote |
| Many apostrophes or long document | `$$ {"a": "it's"} $$` | No escaping needed |
| Single-quoted JSON strings | `'{''a'': 1}'` | Error, JSON needs double quotes |
| Trailing comma | `'{"a": 1,}'` | Error, not valid JSON |
Invalid input
When the text is not valid JSON, the whole statement fails and nothing is stored:
INSERT INTO orders (customer, details)
VALUES ('Linus', '{"status": "paid",}');PostgreSQL reports invalid input syntax for type json along with a detail line that points at the problem. Because the check happens on every insert and update, a jsonb column can never contain malformed JSON.
Values that are not objects
A JSON document does not have to be an object. Any valid JSON value is allowed, including arrays, strings, numbers, booleans, and null:
SELECT '[1, 2, 3]'::jsonb AS an_array,
'"hello"'::jsonb AS a_string,
'42'::jsonb AS a_number,
'true'::jsonb AS a_boolean,
'null'::jsonb AS a_json_null;Notice that the string case needs its own double quotes inside the single quotes. 'hello'::jsonb fails, because hello alone is not valid JSON.
Since the column accepts any JSON value, one row could hold an object and the next an array or a number. Most code assumes objects. A CHECK constraint such as jsonb_typeof(details) = 'object' enforces that. A later chapter shows how.
JSON null and SQL NULL
These are two different things, and mixing them up causes bugs:
- SQL
NULLmeans there is no value in the column. - JSON
nullis a real JSON value, stored like any other.
SELECT 'null'::jsonb IS NULL AS json_null_is_sql_null;This returns false. The stored value null is present, and it just happens to be the JSON null.
The distinction continues inside documents. For a document {"a": null}, asking for key a with the -> operator gives the JSON value null. Asking for a key that does not exist gives SQL NULL. The next chapter covers the operators, but you should know now that "key missing" and "key present with value null" are different states. Pick one convention for your documents and use it consistently.
Converting existing data to JSON
You do not have to type literals by hand. to_jsonb converts any SQL value into jsonb, and it escapes strings for you:
SELECT to_jsonb('it''s fine'::text) AS s,
to_jsonb(42.50::numeric) AS n,
to_jsonb(ARRAY[1, 2, 3]) AS a,
to_jsonb(now()) AS ts;Each result is a valid jsonb value. The string comes out as "it's fine", the array as [1, 2, 3], and the timestamp as an ISO 8601 string. Building whole objects from table columns is the job of jsonb_build_object, which a later chapter covers.
You can also convert in the other direction, from a jsonb value back to its text form, with a cast to text:
SELECT details::text FROM orders WHERE id = 1;This returns the normalized text, not the string you originally inserted.
Passing JSON from application code
Applications should not build SQL by concatenating JSON strings, because that invites quoting bugs and SQL injection. Send the document as a query parameter instead. Parameters keep the data separate from the SQL text, so none of the quote-doubling above applies. The PREPARE statement shows the shape of it:
PREPARE add_order (text, jsonb) AS
INSERT INTO orders (customer, details) VALUES ($1, $2);
EXECUTE add_order('Linus', '{"status": "pending", "total": 7.25, "note": "customer''s request"}');The apostrophe is doubled in the EXECUTE line only because a hand-typed SQL literal needs it. A driver that binds parameters sends the document as is. Most drivers can serialize a native dictionary or object to JSON for you. Check how yours maps a parameter to jsonb. If it sends the value as plain text, add an explicit cast, as in $2::jsonb.
Checking what you stored
Three habits help while you work with a new column:
- Select the column to see the normalized form:
SELECT details FROM orders;. - Use
jsonb_typeof(details)to see what kind of value each row holds. It returnsobject,array,string,number,boolean, ornull. - Use
jsonb_pretty(details)to print a document with indentation, which is easier to read for large values.
SELECT id, jsonb_typeof(details) AS kind, jsonb_pretty(details) AS pretty
FROM orders
ORDER BY id;Summary of edge cases
- Duplicate keys:
jsonbkeeps the last value, andjsonkeeps all of them as text. - Key order and whitespace:
jsonbdoes not preserve either. - Numbers:
jsonbpreserves exact decimal digits, including trailing zeros. \u0000: rejected byjsonb.- Top-level scalars: allowed, so constrain the type if you expect objects.
- JSON
nullis not SQLNULL.
Exercise
Write one INSERT that adds an order for customer 'Linus' with the document {"status": "pending", "note": "customer's request"}, using dollar quoting so the apostrophe needs no escape. Then say what SELECT '{"a": 1, "a": 2}'::jsonb; returns.
Show answer
INSERT INTO orders (customer, details) VALUES ('Linus', $$ {"status": "pending", "note": "customer's request"} $$::jsonb); The SELECT returns {"a": 2}, because jsonb keeps only the last value for a duplicate key.
Exercise
What does SELECT 'null'::jsonb IS NULL; return, and why does SELECT 'hello'::jsonb; fail?
Show answer
The first returns false, because 'null' is a stored JSON null value and not a SQL NULL. The second fails because hello is not valid JSON; a JSON string needs its own double quotes, so the literal must be '"hello"'.