In MariaDB, JSON_MERGE()
is a built-in function that merges two or more JSON documents and returns the result.
The JSON_MERGE()
function has been deprecated, and to avoid future issues, you should use the JSON_MERGE_PATCH()
function instead. The JSON_MERGE_PATCH()
function is an RFC 7396-compliant replacement for JSON_MERGE()
.
Syntax
The syntax goes like this:
JSON_MERGE(json_doc, json_doc[, json_doc] ...)
Where json_doc
are the JSON documents to merge.
Example
Here’s an example to demonstrate.
SELECT JSON_MERGE('{"name":"Wag"}', '{"type":"Dog"}');
Result:
+------------------------------------------------+ | JSON_MERGE('{"name":"Wag"}', '{"type":"Dog"}') | +------------------------------------------------+ | {"name": "Wag", "type": "Dog"} | +------------------------------------------------+
We can see that the two documents have been merged into one.
Here’s an example that merges three documents:
SELECT JSON_MERGE(
'{ "name" : "Wag" }',
'{ "type" : "Dog" }',
'{ "score" : [ 9, 7, 8 ] }'
) AS Result;
Result:
+----------------------------------------------------+ | Result | +----------------------------------------------------+ | {"name": "Wag", "type": "Dog", "score": [9, 7, 8]} | +----------------------------------------------------+
Arrays
One difference between JSON_MERGE()
and JSON_MERGE_PATCH()
is that JSON_MERGE()
merges arrays (JSON_MERGE_PATCH()
does not):
SELECT JSON_MERGE(
'[1,2,3]',
'[4,5,6]'
) AS Result;
Result:
+--------------------+ | Result | +--------------------+ | [1, 2, 3, 4, 5, 6] | +--------------------+
Attempting this with JSON_MERGE_PATCH()
results in only the second array being returned.
Null Argument
If any argument is NULL
, the result is NULL
:
SELECT
JSON_MERGE('{"a":1}', null) AS a,
JSON_MERGE(null, '{"a":1}') AS b,
JSON_MERGE(null, null) AS c;
Result:
+------+------+------+ | a | b | c | +------+------+------+ | NULL | NULL | NULL | +------+------+------+
Incorrect Parameter Count
Calling the function without any arguments results in an error:
SELECT JSON_MERGE();
Result:
ERROR 1582 (42000): Incorrect parameter count in the call to native function 'JSON_MERGE'
It’s the same when you provide just one argument:
SELECT JSON_MERGE('{"a":1}');
Result:
ERROR 1582 (42000): Incorrect parameter count in the call to native function 'JSON_MERGE'