In MariaDB, JSON_MERGE_PRESERVE()
is a built-in function that merges two or more JSON documents and returns the result.
JSON_MERGE_PRESERVE()
is a synonym for JSON_MERGE()
, which has been deprecated. 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_PRESERVE(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_PRESERVE(
'{"name":"Wag"}',
'{"type":"Dog"}'
) AS Result;
Result:
+--------------------------------+ | Result | +--------------------------------+ | {"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_PRESERVE(
'{ "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_PRESERVE()
and JSON_MERGE_PATCH()
is that JSON_MERGE_PRESERVE()
merges arrays (JSON_MERGE_PATCH()
does not):
SELECT JSON_MERGE_PRESERVE(
'[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.
In case you’re wondering, yes JSON_MERGE()
also merges arrays.
Null Argument
If any argument is NULL
, the result is NULL
:
SELECT
JSON_MERGE_PRESERVE('{"a":1}', null) AS a,
JSON_MERGE_PRESERVE(null, '{"a":1}') AS b,
JSON_MERGE_PRESERVE(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_PRESERVE();
Result:
ERROR 1582 (42000): Incorrect parameter count in the call to native function 'JSON_MERGE_PRESERVE'
It’s the same when you provide just one argument:
SELECT JSON_MERGE_PRESERVE('{"a":1}');
Result:
ERROR 1582 (42000): Incorrect parameter count in the call to native function 'JSON_MERGE_PRESERVE'