// strings reference

SQL JSON_OBJECT function

JSON_OBJECT('id': 7, 'total': 42.5) builds {"id":7,"total":42.5}. The standard writes pairs with : or VALUE; MySQL and SQLite separate keys and values with commas.

Kategorie
Strings
Returns
JSON text
In this category
145 of 172

Syntax

JSON_OBJECT(key : value, ...)  -- SQL Server, Oracle, PostgreSQL
JSON_OBJECT(key, value, ...)  -- MySQL, SQLite

Each block is a separate form. The support table and the examples show which engine takes which.

Engine-Unterstützung

EngineSupportNotizen
SQL Server Ja SQL Server 2022+
PostgreSQL Ja JSON_OBJECT on 16+; jsonb_build_object always available
MySQL Ja Supported under this name.
SQLite Ja Supported under this name.
Oracle Ja 12.2+

Beispiele

SQL Server

SELECT JSON_OBJECT('id': id, 'total': total) AS doc
FROM orders;

MySQL

SELECT JSON_OBJECT('region', region, 'tier', tier) AS doc
FROM settings;

SQLite

SELECT json_object('a', 1, 'b', 2) AS doc;

Gut zu wissen

  • The pair separator differs: SQL Server, Oracle and PostgreSQL 16+ take 'key' : value (Oracle and PostgreSQL also 'key' VALUE value); MySQL and SQLite take 'key', value. Oracle rejects the comma form with ORA-02000, and PostgreSQL with a function-not-found error.
  • NULL values are kept as null by default (NULL ON NULL); ABSENT ON NULL drops the member on SQL Server, Oracle and PostgreSQL. Note the opposite default from JSON_ARRAY.
  • Before PostgreSQL 16, use json_build_object(key, value, ...) or jsonb_build_object, which take MySQL's comma-separated shape.

Questions about JSON_OBJECT

How do I turn a whole row into JSON?

PostgreSQL: to_jsonb(t). SQL Server: SELECT ... FOR JSON PATH, WITHOUT_ARRAY_WRAPPER. Oracle: JSON_OBJECT(*). MySQL and SQLite: list the columns as key-value pairs.

Must keys be string literals?

No. A key is any string expression, so JSON_OBJECT(col_name : col_value) builds keys from data. A NULL key is an error rather than a skipped member.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.

// fewer lookups

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.