Referencia · §8.31

JSON

json, §M14.15

Ez az oldal a nucleus saját dokumentációjából készül, ezért angol nyelvű.

One type, json (jsonb another name for it): JSON values, checked when written and kept in a binary form read in place. There is no second type keeping the text as written — a text column does that.

Input (json::parse) is strict RFC 8259: no comments, trailing commas, single quotes, NaN or leading zeros; whitespace is space, tab, line feed and return; \uXXXX escapes with surrogate pairs joined, lone surrogates refused (22P02) and \u0000 refused (22P05: text holds no NUL, so a value’s strings must not); depth at most 1000 (256 in a browser; 54001). Duplicate keys: the last one wins (PostgreSQL’s jsonb). Numbers are exact at any size within numeric’s bounds in PostgreSQL (131 072 digits before the point, 16 383 after; 22003 beyond), but kept as their value, not as written: 1.50 reads back 1.5, 1e2 100, -0 0 (jsonb keeps the scale: 1.50).

The binary form (json::form) is canonical — equal documents, equal bytes, so =, hashing, DISTINCT, GROUP BY and unique keys compare bytes. A node is a header byte (its kind in the high four bits) and its payload: null, false and true the header alone; an integer that fits 64 bits in the fewest little-endian bytes (0–8); any other number a sign, the exponent (zig-zag LEB128), the digit count and the digits two to a byte (digits × 10^exp, no leading or trailing zeros); a string its length (in the header under 15) and UTF-8 bytes; an array its count, the end of each element (1, 2 or 4 bytes, the fewest that hold them) and the elements — a[i] at once; an object its count, the end of each key and of each value, the keys sorted by their bytes, then the values in the keys’ order — a key found by binary search, its value read without the others. Keys sort shorter first, then by their bytes — jsonb’s order, so a value’s text and its place in an order come out as PostgreSQL’s (§M14.15 J2 changed it from bytes alone: a value stored before reads, but compares as unequal to the same document written since). A value inside another is its bytes. Bytes from outside (a key, a corrupted page) are checked before they are a value (form::check: read, written again, compared); a reader refuses a number that could not have been parsed.

Output is PostgreSQL’s jsonb layout — {"a": 1, "b": [1, 2]}, keys in their stored order, strings escaping ", \ and control characters only, numbers in plain notation (0.0000001).

Order (json::key) is PostgreSQL’s: null < string < number < boolean (false < true) < array < object; arrays by length, then element by element; objects by key count, then key and value by key in the keys’ order (a key by its length, then its bytes); strings by their bytes, numbers by value. An order-preserving key encoding makes json a primary key or an indexed column, range scans included.

Casts: from text (the input) and to text (the output); to boolean, the integers, numeric, real and double precision from a json value of that kind ('42'::json::int; another kind is 22023, cannot cast json string to type integer; a number past numeric’s 38 digits is 22003).

Operators (json::ops, json::funcs; PostgreSQL’s jsonb ones, checked against PostgreSQL 18 by slt/65_json.slt):

j -> 'k', j -> 2 a field, an element (negative: from the end); NULL when missing or not of that kind
j ->> 'k', j ->> 2 the same as text: a string’s own text, NULL for null
j #> '{a,0}', j #>> '{a,0}' at a path of keys and positions
a @> b, b <@ a containment: every key of an object with a containing value, each element of an array in some element; a top-level array contains its scalar elements
j ? 'k', ?|, ?& a key, or a string element, exists — any, all of a text[]
a || b objects merged (the right’s keys win), arrays concatenated, a value appended or prepended to an array, two others an array of both
j - 'k', j - '{k,l}'::text[], j - 2 without the keys (strings, for an array), without the element
j #- '{a,0}' without the value at a path

A chain of -> by constant keys or positions, ending in -> or ->> (doc -> 'address' -> 'geo' ->> 'lat'), is bound as one call, ->(json,path) / ->>(json,path) (EXPLAIN shows it): the document’s bytes walked to the value, no value between copied out — each -> alone copies its value (PLAN.md §M15 D1). #> / #>> by a constant path none of whose keys reads as an integer (doc #> '{address,geo}') are bound as the chain they mean (json::funcs::Path::of_array), so an expression index on either spelling serves both (§M15 D4); a key reading as an integer indexes an array under #> but not under ->, so such a path is left as it is. #>, #>>, ?|, ?& and json_extract_path read their keys in place, nothing copied a row.

An untyped right side (doc -> 'name', doc -> $1) is text where the operator has a text form (as PostgreSQL’s unknown), else the type its only form takes (#> '{a,b}': text[]) — the binder’s rule for any registered operator (Registry::operand_for); -, the grammar’s own operator, takes a right side of another type through the type’s arithmetic (Arithmetic::other_operand).

Functions, each also under its jsonb_ name: json_typeof, json_array_length, json_pretty (empty containers on two lines, as jsonb_pretty), json_strip_nulls(j [, in_arrays]), to_json (numbers as numbers — a float’s non-finite values as strings —, times in ISO 8601, arrays as arrays, anything else its text as a string), json_build_object(k, v, …), json_build_array(…), json_object(text[] [, text[]]), json_set(j, path, new [, create]) and json_insert(j, path, new [, after]) (a position out of range adds at that end), json_extract_path(j, k, …) and _text; in FROM, json_each, json_each_text, json_array_elements, json_array_elements_text (their columns key, value; with one column, the alias names it too, as PostgreSQL’s whole-row reference to a scalar result is the value: FROM json_array_elements(x) e WHERE e ->> 'k' = …, a hidden copy out of *) and json_object_keys; aggregates json_agg(x) (NULLs as null) and json_object_agg(k, v). Errors are PostgreSQL’s (22023 cannot delete from scalar, 22P02 path element at position 1 is not an integer: "x", 22004 a NULL path step or key, 2202E uneven arrays). Not there yet: arrays of json (no json[]), row_to_json (no row values: json_build_object), set-returning functions in the select list (PostgreSQL’s SELECT json_each(j): in FROM), and jsonb’s raw-scalar quirk ('1'::jsonb -> 0 is 1 there, NULL here).

SQL/JSON paths (json::path, §M14.15 J3a): PostgreSQL’s jsonpath — a type of its own ('$.a[*] ? (@ > 1)'::jsonpath), kept as its normalized text (keys and variables quoted, lax left out, operators parenthesized by priority: $."a"[*]?(@ > 1); a number or an operator followed by accessors is parenthesized wherever it stands, where PostgreSQL’s text drops the parentheses inside a filter and reads back as another path). The language (json::path::parse, one token of look-ahead): $, @ (in a filter only), $name and $"name" variables, last (in a subscript only), literals (numbers as numeric, also 0x1F, 0o17, 0b101, 1_000; strings with \x41, \u{1F600} and \v); accessors .key, ."key", .*, [*], [i, j to k], .**, .**{n}, .**{n to m} (last as a level), filters ?( … ); + - * / % and unary signs (a sign on a number folds into it); predicates == != <> < <= > >=, && || !, exists( … ), ( … ) is unknown, starts with a string or a variable, like_regex "…" flag "ismq" (x is 0A000, as PostgreSQL’s; compiled once, with the regex crate); methods .type() .size() .double() .ceiling() .floor() .abs() .keyvalue() .bigint() .boolean() .integer() .number() .string() .decimal(p, s) .datetime([template]) .date() .time([p]) .time_tz([p]) .timestamp([p]) .timestamp_tz([p]); keywords in any case but true, false and null; /* comments */. Refused as PostgreSQL refuses (42601, 2201B, 0A000, 22P05); a path whose tree nests more than 128 levels — filters, subscripts, signs, a chain of && or + (which nests to the left) — is 54001: the printer, the evaluator and the tree’s drop recurse once a level, and the parser, allowed twice as deep, reads back every normalized text it gives (PostgreSQL’s limit is its stack’s).

Evaluation (json::path::eval) is PostgreSQL’s executor step for step: lax mode (the default) unwraps an array for an accessor, a filter or a method, wraps a scalar for […], and ignores structural errors (a missing key, a subscript out of range); strict mode raises them (2203A, 2203C, 22033, 22039). Items are slices of the document read in place (or of a variable, or of a value the path made), or datetimes. Predicates are three-valued: items of different kinds are unknown (but null is unequal to everything else), containers unknown, strings by their bytes, numbers by value; an error inside a predicate is unknown; lax mode answers at the first true, strict at the first unknown. Arithmetic wants one number a side (22038; 22012 division by zero), on numeric (38 digits: a number past them is 22003). .** goes depth-first, a value before its children. .keyvalue()’s id is 0 for the outermost object and its byte offset otherwise (an offset in nucleus’s form, not in PostgreSQL’s). Datetimes (json::path::datetime): .datetime() tries PostgreSQL’s ISO 8601 forms in its order; a template is to_timestamp’s (YYYY YYY YY Y MM DD Mon Month Dy Day HH24 HH12 HH MI SS MS US FF1–FF6 AM PM A.M. P.M. TZH TZM TZ "text"; separators must match, a zone is Z, UTC, GMT, UT or an offset); they compare across kinds where PostgreSQL’s do, a comparison or cast that needs a zone is 0A000 outside the _tz functions (whose zone is the session’s, UTC); an item prints as ISO 8601 (2020-01-01T10:00:00+03:00).

Functions, each also under a jsonb_ name and with a _tz form (stable): json_path_exists(j, path [, vars [, silent]]), json_path_match (the path’s single boolean, NULL when unknown; 22038 otherwise), json_path_query_array, json_path_query_first, and in FROM json_path_query (a row an item). vars is an object (22023 otherwise); a missing variable is 42704 even when silent; silent hides the evaluation’s errors and returns what was found before one, as PostgreSQL’s. Operators j @? path (exists) and j @@ path (match), both silent. A path value is parsed once per thread while it is among the last 16 (json::path::compiled). Differences, recorded in slt/66_json_path.slt: numbers keep no scale (2 * 3.5 is 7, PostgreSQL’s 7.0), .keyvalue()’s ids below the root, the parenthesized text above.

SQL/JSON’s functions (json::sqljson, §M14.15 J3b), written with the standard’s keywords, which the parser desugars into calls of functions (__json_value, …) whose options are constant arguments: JSON_EXISTS(ctx, path [PASSING v AS name, …] [{TRUE | FALSE | UNKNOWN | ERROR} ON ERROR]), JSON_VALUE(ctx, path [PASSING …] [RETURNING t] [{NULL | ERROR | DEFAULT x} ON EMPTY] [… ON ERROR]) (one scalar: 2203F for a container, 22034 for more than one item, a boolean as t/f, JSON null as NULL), JSON_QUERY(ctx, path [PASSING …] [RETURNING t] [WITH [CONDITIONAL | UNCONDITIONAL] [ARRAY] WRAPPER | WITHOUT WRAPPER] [{KEEP | OMIT} QUOTES [ON SCALAR STRING]] [{NULL | ERROR | EMPTY [ARRAY] | EMPTY OBJECT | DEFAULT x} ON EMPTY] [… ON ERROR]) (json by default; a conditional wrapper wraps more than one item); the context is json or text read as it (a text that is not JSON is an error whatever ON ERROR says, as PostgreSQL’s); PASSING values become the path’s variables as to_json makes them. ON EMPTY defaults to NULL; ON ERROR to NULL (FALSE for JSON_EXISTS); ERROR ON EMPTY is not caught by ON ERROR; a missing variable is 42704 always. RETURNING t is given as a typed NULL (the witness) whose type the call takes; when the call is bound, ScalarFunction::rewrite reads the type and its modifier off the bound witness and gives the call specialized to it, which converts the result itself — by t’s input from the scalar’s text (1.5 is no int: 22P02), checking varchar(n) and char(n) lengths (22001, not cut as a cast cuts) and numeric(p, s) (22003) — so that a conversion’s error is ON ERROR’s. Specialized, a call is immutable (stable when it returns timestamptz). x IS [NOT] JSON [VALUE | ARRAY | OBJECT | SCALAR] [WITH | WITHOUT UNIQUE [KEYS]] on text, bytea or json (42804 for another type; a key twice anywhere refused with UNIQUE, compared after escapes are read: json::parse::parse_checked). Constructors: JSON_OBJECT(k VALUE v | k : v, … [NULL | ABSENT ON NULL] [WITH | WITHOUT UNIQUE [KEYS]] [RETURNING t]) (NULL ON NULL by default; a NULL key 22004; a key twice 22030 with UNIQUE, even when its value is left out; with neither VALUE nor : it is PostgreSQL’s older json_object(text[])), JSON_ARRAY(v, … [ABSENT | NULL ON NULL] [RETURNING t]) (ABSENT by default) and JSON_ARRAY(query) ((SELECT JSON_ARRAYAGG(x) FROM (query) q(x)), as PostgreSQL reads it: NULL over no rows), JSON_OBJECTAGG(k VALUE v …), JSON_ARRAYAGG(v [ORDER BY …] …) (NULL over no rows, [] over rows all left out), JSON(text [WITH UNIQUE KEYS]), JSON_SCALAR(x) (to_json), JSON_SERIALIZE(x [RETURNING t]); v FORMAT JSON reads text as JSON. Differences, recorded in slt/67_json_sql.slt (207 records as PostgreSQL 18 gives them): json is one canonical type, so a constructor’s text is jsonb’s ({"a": 1}, sorted keys, the last of equal keys, no scale on numbers) where PostgreSQL’s json keeps its own layout ({"a" : 1}); JSON_SERIALIZE of a json value gives its text (PostgreSQL 18 gives jsonb’s binary form read as text); a PASSING date is its ISO string (PostgreSQL passes a datetime item).

JSON_TABLE (§M14.15 J3c), in FROM: JSON_TABLE(ctx, path [AS name] [PASSING …] COLUMNS (name FOR ORDINALITY | name type [FORMAT JSON] [PATH 'p'] [wrapper] [quotes] [… ON EMPTY] [… ON ERROR] | name type EXISTS [PATH 'p'] [… ON ERROR] | NESTED [PATH] 'p' [AS name] COLUMNS (…), …) [ERROR | EMPTY [ARRAY] ON ERROR]) [AS alias [(names)]]. The parser desugars it (parser.rs, json_table) into a lateral subquery: the row path’s items come from __json_table_rows(ctx, path, vars, error) (item, ord from 1; a failing row path gives no rows, or its error with ERROR ON ERROR); a column is JSON_VALUE of the item — JSON_QUERY when it is FORMAT JSON, has a wrapper or quotes, or is of type json —, JSON_EXISTS cast to its type, or the item’s position; a column without PATH reads $."name". A column’s ON ERROR is its own (NULL by default, whatever the table’s). NESTED PATH is PostgreSQL’s default plan: a lateral LEFT JOIN of the nested rows (a parent without them keeps a row of NULLs), sibling NESTEDs’ rows UNION ALLed, each with the others’ columns NULL; the rows come in the document’s order. Column names are unique (42712). One difference, recorded in slt/68_json_table.slt (67 records as PostgreSQL 18 gives them): a DEFAULT may read the row’s columns (PostgreSQL refuses column references there).

Indexes on JSON (§M14.15 J4a): an expression index on a path’s value — CREATE INDEX ON t ((doc->>'kind')), (((doc->>'age')::int)), ((JSON_VALUE(doc, '$.id' RETURNING int))) — serves equalities and ranges on that very expression (§8.7’s expression indexes).

The containment index (§M14.15 J4b, text::index::json): CREATE INDEX [name] ON t USING json (doc [json_ops]) serves a filter’s doc @> q, doc ? k, doc ?| ks and doc ?& ks, the right side fixed for the scan. It is the text index’s storage (§8.19: delta, tombstones, seals, merges, snapshots, the integrity check, erasure’s scrub) with weighted documents (each term 1, no positions), whose terms are hashes (object_cache::object_id, kinds 15–17, 16 hex digits): a leaf’s of its path — the object keys from the root, an array’s elements on their array’s path — and its canonical value bytes (PostgreSQL’s jsonb_path_ops), and a key path’s, of the path through an object’s key. doc @> q looks for q’s leaves, and its key paths only above an empty object or array (a leaf below a key implies the key, and a key path’s postings are long); doc ? k for the top-level key k or k as a string at the top (an element of a top-level array, or the document); ?| any, ?& all of those. The index is lossy — two values may hash alike, and terms tell paths, not which element of an array holds what ({"a": [{"b": 1}, {"c": 2}]} has every term of {"a": [{"b": 1, "c": 2}]}) — so it says it is not exact (IndexMethod::exact, §8.17) and the condition stays in the scan’s filter, checked on each row found. A q with nothing to look for ({}, []) or a NULL is not served (every row is read; NULL matches none). Unlike jsonb_path_ops it serves ?, and @> of an empty container under a key. EXPLAIN: Index Scan using ix on t (doc @> {…}) filter: ….

JSON Schema (§M14.15 J5, json::schema): json_matches_schema(doc, schema) (jsonb_matches_schema too, pg_jsonschema’s name) says whether a document fits a schema, so CHECK (json_matches_schema(args, '…')) refuses a model’s tool call or structured output that does not (23514); json_schema_errors(doc, schema) is text[], each problem with its place — $.days: 30 is greater than the maximum 14, $: the required property "city" is missing, $.hours[1]: expected integer, got string —, in the document’s key order, every one of them (where json_matches_schema stops at the first). The vocabulary is JSON Schema 2020-12’s validation and applicators: type (a name or names; integer is any number without a fraction, 1.0 too), enum, const, minimum / maximum / exclusiveMinimum / exclusiveMaximum (exact: the numbers’ order keys, §8.31’s order), multipleOf (exact in decimals where both numbers’ digits fit 128 bits, else in f64), minLength / maxLength (characters), pattern (the regex crate: ECMA-262’s without look-around or back-references), items, prefixItems, contains / minContains / maxContains, minItems / maxItems, uniqueItems, properties, patternProperties, additionalProperties, propertyNames, required, dependentRequired, dependentSchemas, minProperties / maxProperties, allOf, anyOf, oneOf, not, if / then / else, and $ref — a JSON Pointer into the schema (#, #/$defs/node, recursion too; a check deeper than 256 is 54001, a loop’s end). Equality (enum, const, uniqueItems) compares canonical bytes: equal values have equal bytes. Annotations are passed over (title, description, default, examples, format, $schema, $id, $comment, deprecated, readOnly, writeOnly, content*, x-…, Gemini’s propertyOrdering), and OpenAPI’s nullable: true admits null; any other keyword is refused (0A000) rather than ignored, so a misspelt requried is an error, not a schema every document fits — unevaluatedProperties, unevaluatedItems, $dynamicRef, items as an array (draft 4–2019’s; prefixItems instead) and a $ref to another document among them. A schema that is not one ({"type": "text"}, a pattern that does not compile, a $ref pointing nowhere) is 22023. A schema is compiled once — subschemas in an arena, a $ref’s target shared by its pointer — and kept per thread by its bytes (64 at most), so a CHECK’s constant schema is compiled once per thread. Prior art: pg_jsonschema (Supabase’s extension, the function names) and the jsonschema crate (a schema compiled to a tree of validators); PLAN.md §M14.15 J5.

MCP (§6.5) sends a json column’s value as the JSON itself.

On the wire (ncp tag 11 named json) a value travels as its text (Type::wire_output / wire_input), in rows and in columnar batches; the drivers hand out the language’s own values (§11). pg-compat shows it as jsonb (§9). Tests: json::tests (round trips, canonical bytes, malformed text and bytes, the order, wide containers), tests/json.rs (stored and read back, a key and an index, DISTINCT and GROUP BY, casts and errors), slt/65_json.slt (the operators and functions, 108 records as PostgreSQL 18 gives them: scripts/slt-pg.py check), json::path::tests (texts and errors as PostgreSQL’s, evaluation), slt/66_json_path.slt (paths, 221 records as PostgreSQL 18 gives them), slt/67_json_sql.slt (SQL/JSON’s functions, 207 records as PostgreSQL 18 gives them), slt/68_json_table.slt (JSON_TABLE, 67 records), slt/69_expression_indexes.slt (expression indexes, on JSON paths among others), slt/70_json_index.slt (the containment index: its conditions’ results as PostgreSQL 18 gives them, a recheck’s false match, writes, sealed segments), json::schema::tests and slt/71_json_schema.slt (JSON Schema: each keyword, the errors’ places, a CHECK, what is refused), text::index::json::tests (no contained document missed, paths and values told apart), the law kit’s generator (equal documents written differently), the json fuzz target (§2; the operators’ laws too, and paths: normalized text reads back as itself, items are canonical), pg-compat’s json_through_a_real_driver. Measurements: PLAN.md §M14.15 J1–J3c and docs/benchmarks.md.