JSON_OBJECTAGG

MariaDB starting with 10.5.0

JSON_OBJECTAGG was added in MariaDB 10.5.0.

Syntax

JSON_OBJECTAGG(key, value)

Description

JSON_OBJECTAGG returns a JSON object containing key-value pairs. It takes two expressions that evaluate to a single value, or two column names, as arguments, the first used as a key, and the second as a value.

The maximum returned length in bytes is determined by the group_concat_max_len server system variable.

Returns NULL in the case of an error, or if the result contains no rows.

JSON_OBJECTAGG cannot currently be used as a window function.

Examples

select * from t1;
+------+-------+
| a    | b     |
+------+-------+
|    1 | Hello |
|    1 | World |
|    2 | This  |
+------+-------+

SELECT JSON_OBJECTAGG(a, b) FROM t1;
+----------------------------------------+
| JSON_OBJECTAGG(a, b)                   |
+----------------------------------------+
| {"1":"Hello", "1":"World", "2":"This"} |
+----------------------------------------+

Comments

 
10 months, 1 week ago Carlos Lopez

Repeated JSON Keys are valid and allowed in spec. It's just that most parsers of JSON will replace the previous key with the last one noted. In Javascript itself, you can parse as a array of [key, value] called "entries", but the default parser (JSON.parse) won't give you this.

 
2 years ago Norman Rice

How is this resulting JSON in the example what we would want? -- {"1":"Hello", "1":"World", "2":"This"} --

  • The attribute '1' is repeated. That's not valid.
  • In cases where parsers are a bit more lenient, they probably discard the 'Hello', and override it with 'World'.

A more useful JSON result would be: -- {"1":["Hello","World"], "2":"This"} --

Or, if the function is expanded to take an additional third parameter JSON_OBJECTAGG(key, value,optional_keyfield_for_duplicate_values):

-- select * from t1; +------+-------+------+

abc

+------+-------+------+

1HelloA
1WorldB
2Thisnull

+------+-------+------+

SELECT JSON_OBJECTAGG(a, b, c) FROM t1; +---------------------------------------------+

JSON_OBJECTAGG(a, b, c)

+---------------------------------------------+

{"1":["A":"Hello","B":"World"], "2":"This"}

+---------------------------------------------+

--

 
Content reproduced on this site is the property of its respective owners, and this content is not reviewed in advance by MariaDB. The views, information and opinions expressed by this content do not necessarily represent those of MariaDB or any other party.
Back to Top