JSON_OBJECT()
This page is part of MariaDB's Documentation.
The parent of this page is: Functions for MariaDB Xpand
Topics on this page:
Overview
Returns a JSON object created from key/value pairs.
USAGE
JSON_OBJECT([key, value[, key, value] ...])
Argument Name | Description |
---|---|
| A dictionary key for the associated value |
| A value associated with the preceding key |
DETAILS
JSON_OBJECT()
is a JSON construction function that accepts key/value pairs of arguments and returns a JSON object.
A JSON object is a string representation of a dictionary of keys that each have an associated value:
The representation begins with
{
and ends with}
Each key is a double-quoted string that is followed by a colon and a value that can be any JSON data type
Multiple key/value pairs are separated by commas
Space characters outside of double quotes are ignored
Although the currently implementation allows a duplicate key to be added to the same object, this should be avoided because only the first such key in an object can be retrieved in a path expression.
When no arguments are provided, an empty JSON object is returned.
IF a NULL
is specified for the key, it is rejected with an error.
EXAMPLES
With Literal Values
In the following example, JSON_OBJECT()
is called with multiple sets of literal values as key-value pairs. The result demonstrates how to create a simple JSON object:
SELECT JSON_OBJECT('bar', 42, 'baz', 86, 'foo', 'all done for now') AS result;
+---------------------------------------------------+
| result |
+---------------------------------------------------+
| {"bar": 42, "baz": 86, "foo": "all done for now"} |
+---------------------------------------------------+
Example Schema and Data
Some of the examples are based on the inventory
table:
CREATE TABLE inventory (
item VARCHAR(20),
category VARCHAR(20),
count INT
);
INSERT INTO inventory VALUES
('Foo','in stock', 42), ('Foo','back order', 50),
('Bar','in stock', 10), ('Bar','back order', 60),
('Baz','in stock', 99), ('Baz','back order', 10);
Per-row Values
SELECT JSON_OBJECT(
'item', item,
'count', count
) AS result
FROM inventory
WHERE category = 'in stock' AND count > 5 \G
*************************** 1. row ***************************
result: {"item": "Foo", "count": 42}
*************************** 2. row ***************************
result: {"item": "Bar", "count": 10}
*************************** 3. row ***************************
result: {"item": "Baz", "count": 99}