SQL to_json function
to_jsonb(u) turns a whole row into a JSON object keyed by column name; to_jsonb(42) turns a scalar into JSON. SQLite's json() and MySQL's CAST AS JSON parse text instead.
- Catégorie
- Strings
- Returns
JSON or jsonb- In this category
- 161 of 172
Syntaxe
to_json(expr)
to_jsonb(expr) -- PostgreSQL
json(x) -- SQLite
Each block is a separate form. The support table and the examples show which engine takes which.
Prise en charge des moteurs
| Moteur | Support | Notes |
|---|---|---|
| SQL Server | Different name or syntax | no to_json; FOR JSON builds documents |
| PostgreSQL | Oui | Supported under this name. |
| MySQL | Different name or syntax | CAST(x AS JSON) validates; JSON_ARRAY/JSON_OBJECT build |
| SQLite | Oui | Supported under this name. |
| Oracle | Different name or syntax | JSON_OBJECT and constructors; no single to_json |
Exemples
PostgreSQL
SELECT to_jsonb(u) AS doc FROM users u;
SQLite
SELECT json(value) AS normalised FROM imports;
MySQL
SELECT CAST(info AS JSON) AS checked FROM staging;
Bon à savoir
- to_json returns json (text, keeps duplicate keys and key order) and to_jsonb returns jsonb (parsed binary, sorted keys, supports @>, ? and GIN indexes). Prefer jsonb for anything you will query.
- SQLite's json() parses its argument and returns minified canonical JSON. It errors on invalid input, and it converts JSON5 such as {a:1} to {"a":1}.
- to_jsonb of a text value makes a JSON string: to_jsonb('{"a":1}'::text) is the string "{\"a\":1}", not an object. To parse text, cast it: '{"a":1}'::jsonb.
- SQL Server builds documents with FOR JSON rather than a function; row-to-JSON there is SELECT ... FOR JSON PATH, WITHOUT_ARRAY_WRAPPER.
Questions about to_json / JSON()
Row to JSON in one call?
PostgreSQL: to_jsonb(table_alias). SQL Server: FOR JSON PATH, WITHOUT_ARRAY_WRAPPER. Oracle: JSON_OBJECT(*). MySQL and SQLite: JSON_OBJECT listing the columns.
json or jsonb on PostgreSQL?
jsonb for anything stored and queried: indexes, containment, operators. json only when the exact original text must survive, duplicates and key order included.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.
Functions your engine actually has
SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.