JSON type
The JSON column type in the MySQL and MariaDB dialects: validation, storage as text, paths and the differences from the servers.
Syntax#
column_name JSON [NOT NULL] [DEFAULT ...]Remarks#
- Validation. A value written into a
JSONcolumn must be valid JSON. If it is not, the statement fails with error 3140 (JSON parse problem "..." at position n while storing a value for column 't.j'.), with MySQL's words for the fault:The document is empty.,Missing a name for object member.,Missing a comma or ']' after an array element., and so on. For example{bad, the empty text,[1, 2,{"a" 1},{"a": 1 "b": 2},[1, 2] x,abc,"abcand[1,]all give MySQL 9.7's text. - Storage. Raft DB keeps the document as the text it was given (the text is checked, not rewritten). MySQL converts it to a binary form and reorders the members of objects; MariaDB's
JSONis an alias ofLONGTEXTwith a validity check, which is closer to Raft DB. SHOW CREATE TABLEandDESCRIBEshow the type asjson.- Functions. See JSON functions. Paths use
$,.key,[n],[last],[a to b],.*,[*]and**.CAST(x AS JSON)marks a value as a document. - Operators.
->,->>andMEMBER OFin the MySQL dialect; see JSON operators. - Indexes. Functional indexes and generated columns over a
JSONexpression are covered on CREATE TABLE statement. - Aggregate.
JSON_ARRAYAGGbuilds an array from the rows of a group. - Invalid text from other places. In a function call a text that is not JSON gives error 3141 in the MySQL dialect and
NULLin the MariaDB dialect.
Examples#
CREATE TABLE j (id INT PRIMARY KEY, d JSON);
INSERT INTO j VALUES (1, '{"a": 1, "b": "x", "c": [1, 2, 3], "n": {"k": "v"}}'), (2, '{"a": 2, "b": "y"}');
SELECT id, d->'$.a', d->>'$.b', d->'$.c[1]', d->>'$.n.k' FROM j; -- MySQL dialect
SELECT id, JSON_EXTRACT(d, '$.a'), JSON_UNQUOTE(JSON_EXTRACT(d, '$.b')) FROM j;
INSERT INTO j VALUES (3, '{bad'); -- error 3140