In MariaDB, JSON_VALID()
is a built-in function that allows you to check whether or not a value is a valid JSON document.
You pass the value as an argument, and JSON_VALID()
returns 1
if it’s a valid JSON document, and 0
if not.
Syntax
The syntax goes like this:
JSON_VALID(value)
Example
Here’s an example to demonstrate.
SELECT JSON_VALID('{ "product" : "Cup" }');
Result:
+-------------------------------------+ | JSON_VALID('{ "product" : "Cup" }') | +-------------------------------------+ | 1 | +-------------------------------------+
In this case, the argument is a valid JSON document.
Here’s what happens if we remove part of the document:
SELECT JSON_VALID('{ "product" }');
Result:
+-----------------------------+ | JSON_VALID('{ "product" }') | +-----------------------------+ | 0 | +-----------------------------+
Now it’s not a valid JSON document.
Arrays
Arrays are considered a valid JSON document.
Example:
SELECT JSON_VALID('[ 1, 2, 3 ]');
Result:
+---------------------------+ | JSON_VALID('[ 1, 2, 3 ]') | +---------------------------+ | 1 | +---------------------------+
Null Arguments
If the argument is NULL
, the result is NULL
:
SELECT JSON_VALID(null);
Result:
+------------------+ | JSON_VALID(null) | +------------------+ | NULL | +------------------+
Incorrect Parameter Count
Calling JSON_VALID()
without an argument results in an error:
SELECT JSON_VALID();
Result:
ERROR 1582 (42000): Incorrect parameter count in the call to native function 'JSON_VALID'
It’s the same when you provide too many arguments:
SELECT JSON_VALID('a', 'b');
Result:
ERROR 1582 (42000): Incorrect parameter count in the call to native function 'JSON_VALID'