This topic describes the JSON functions that are supported by AnalyticDB for MySQL clusters.
JSON_ARRAY_CONTAINS: Checks whether a JSON array contains the specified
value.JSON_ARRAY_LENGTH: Returns the length of a JSON array.
JSON_CONTAINS (for versions 3.1.5.0 and later): Checks whether the specified path contains the
candidatevalue. If no path is specified, this function checks whether the target contains thecandidatevalue.JSON_CONTAINS_PATH (for versions 3.1.5.0 and later): Checks whether a JSON document contains any or all of the specified paths.
JSON_EXTRACT: Extracts data from a JSON document at the specified
json_path.JSON_KEYS: If
json_pathis specified, this function returns all keys from the specified path of a JSON document. Ifjson_pathis not specified, this function returns all keys from the root path (json_path='$').JSON_OVERLAPS (for versions 3.1.10.6 and later): Checks whether a JSON document contains any of the specified elements, such as
candidate1,candidate2, orcandidate3.JSON_REMOVE (for versions 3.1.10.0 and later): Removes the element at the specified
json_pathfrom ajsondocument and returns the modified string. You can specify multiple elements to remove using `array[json_path,json_path,...]`.JSON_SIZE: Returns the size of the JSON object or array at the specified
json_path.JSON_SET (for versions 3.2.2.8 and later): Inserts or updates data in a
jsondocument at the specifiedjson_pathand returns the updatedjsondocument.JSON_UNQUOTE (versions 3.2.2.11 and later): Removes the double quotation marks from
json_value, unescapes specific escape characters injson_value, and returns the resulting value.
JSON_ARRAY_CONTAINS
json_array_contains(json, value)Description: Checks whether a JSON array contains the specified
value.Input value type:
valuecan be a numeric type, string, or BOOLEAN.Return value type: BOOLEAN.
Example:
Check whether the JSON array
[1, 2, 3]contains the element `2`. The statement is as follows:SELECT json_array_contains('[1, 2, 3]', 2);The following result is returned:
+-------------------------------------+ | json_array_contains('[1, 2, 3]', 2) | +-------------------------------------+ | 1 | +-------------------------------------+
JSON_ARRAY_LENGTH
json_array_length(json)Description: Returns the length of a JSON array.
Input value type: String or JSON.
Return value type: BIGINT.
Example:
Return the length of the JSON array
[1, 2, 3]. The statement is as follows:SELECT json_array_length('[1, 2, 3]');The following result is returned:
+--------------------------------+ | json_array_length('[1, 2, 3]') | +--------------------------------+ | 3 | +--------------------------------+
JSON_CONTAINS
The `JSON_CONTAINS` function checks whether a specified JSON document contains a specific value. You can use a JSON array index in your queries to avoid full table scans or parsing of the entire JSON document, which improves query efficiency.
Without a JSON index
This syntax is supported only in clusters with a kernel version of 3.1.5.0 or later.
To view and update the minor version, go to the Configuration Information section on the Cluster Information page in the AnalyticDB for MySQL console.
json_contains(target, candidate[, json_path])Description:
If
json_pathis specified, this function checks whether the specified path contains thecandidatevalue. It returns `1` if the value is contained and `0` otherwise.If
json_pathis not specified, this function checks whether the target contains thecandidatevalue. It returns `1` if the value is contained and `0` otherwise.
The rules are as follows:
If both
targetandcandidateare primitive types (NUMBER, BOOLEAN, STRING, or NULL), the target is considered to contain the candidate if they are equal.If both
targetandcandidateare JSON arrays, the target is considered to contain the candidate if all elements of `candidate` are contained in any element of `target`.If
targetis an array andcandidateis not an array, the target is considered to contain the candidate if `candidate` is contained in any element of `target`.If both
targetandcandidateare JSON objects, the target is considered to contain the candidate if every key in `candidate` is also in `target`, and the value for each key in `candidate` is contained in the value for the corresponding key in `target`.
Input value type:
targetandcandidateare of the JSON type.json_pathis of the JSONPATH type.Return value type: BOOLEAN.
Examples:
Check whether the path
$.acontains the value `1`. The statement is as follows:SELECT json_contains(json '{"a": 1, "b": 2, "c": {"d": 4}}', json '1', '$.a') as result;The following result is returned:
+--------+ | result | +--------+ | 1 | +--------+Check whether the path
$.bcontains the value `1`. The statement is as follows:SELECT json_contains(json '{"a": 1, "b": 2, "c": {"d": 4}}', json '1', '$.b') as result;The following result is returned:
+--------+ | result | +--------+ | 0 | +--------+Check whether
{"d": 4}is contained in the target. The statement is as follows:SELECT json_contains(json '{"a": 1, "b": 2, "c": {"d": 4}}', json '{"d": 4}') as result;The following result is returned:
+--------+ | result | +--------+ | 0 | +--------+
Using a JSON array index
This syntax is supported only in clusters with a kernel version of 3.1.10.6 or later.
A JSON array index must be created for the specified JSON column. For more information, see Create a JSON array index.
You can add
EXPLAINbefore your SQL query statement to view the execution plan. If the execution plan does not contain the `ScanFilterProject` operator, the JSON array index was used successfully. Otherwise, the index was not used.
json_contains(json_path, cast('[candidate1,candidate2,candidate3]' as json)) Description: Checks whether the specified JSON document contains all specified elements, such as
candidate1,candidate2, andcandidate3.Data types of the input values: The values
candidate1,candidate2,candidate3,...must all be of the same data type, either numeric or string.Return value type: VARCHAR.
Examples:
Check whether the specified JSON column
vjcontainsCP-018673andCP-018671.SELECT json_contains(vj, cast('["CP-018673","CP-018671"]' AS json)) FROM json_test;The following result is returned:
+------------------------------------------------------------+ |json_contains(vj, cast('["CP-018673","CP-018671"]' AS json))| | +------------------------------------------------------------+ | 0 | +------------------------------------------------------------+ | 0 | +------------------------------------------------------------+ | 1 | +------------------------------------------------------------+ | 0 | +------------------------------------------------------------+ | 0 | +------------------------------------------------------------+Check whether the specified JSON column
vjcontainsCP-018673,1, and2.SELECT json_contains(vj, cast('["CP-018673",1,2]' AS json)) FROM json_test;The following result is returned:
+------------------------------------------------------------+ |json_contains(vj, cast('["CP-018673","CP-018671"]' AS json))| | +------------------------------------------------------------+ | 0 | +------------------------------------------------------------+ | 1 | +------------------------------------------------------------+ | 1 | +------------------------------------------------------------+ | 0 | +------------------------------------------------------------+ | 1 | +------------------------------------------------------------+
JSON_CONTAINS_PATH
json_contains_path(json, one_or_all, json_path[, json_path,...])This function is supported only in clusters with a kernel version of 3.1.5.0 or later.
To view and update the minor version, go to the Configuration Information section on the Cluster Information page in the AnalyticDB for MySQL console.
Command description: Checks if the specified path exists in the JSON object.
If
one_or_allis set to'one', the function returns `1` if the JSON document contains any of the specified paths. Otherwise, it returns `0`.If
one_or_allis set to'all', the function returns `1` if the JSON document contains all of the specified paths. Otherwise, it returns `0`.
Input value type:
jsonis of the JSON type.one_or_allis of the VARCHAR type and can be'one'or'all'(case-insensitive).json_pathis a path expression.Return value type: BOOLEAN.
Examples:
Check whether the JSON document contains at least one of the paths
$.aand$.e. The statement is as follows:SELECT json_contains_path(json '{"a": 1, "b": 2, "c": {"d": 4}}', 'one', '$.a', '$.e') AS RESULT;The following result is returned:
+--------+ | result | +--------+ | 1 | +--------+Check whether the JSON document contains both of the paths
$.aand$.e. The statement is as follows:SELECT json_contains_path(json '{"a": 1, "b": 2, "c": {"d": 4}}', 'all', '$.a', '$.e') AS RESULT;The following result is returned:
+--------+ | result | +--------+ | 0 | +--------+
JSON_EXTRACT
The return value of the `JSON_EXTRACT` function, similar to columns of the JSON type, does not support
ORDER BY.When using the `JSON_EXTRACT` function with the `JSON_UNQUOTE` function, you must first use CAST AS VARCHAR to convert the return value of `JSON_EXTRACT` to the VARCHAR type. The converted value can then be used as an input parameter for the `JSON_UNQUOTE` function.
json_extract(json, json_path)Description: Extracts a value from a JSON document at the specified
json_path. If a key in thejsondocument contains special characters, such as$or., thejson_pathformat must be'$["Key"]'.For example, if the key is
$data, `json_path` must be'$["$data"]'.Input value type: String or JSON.
Return value type: JSON.
Examples:
Return the value at path `$[0]` from the array
[10, 20, [30, 40]]. The statement is as follows:SELECT json_extract('[10, 20, [30, 40]]', '$[0]');The following result is returned:
+-------------------------------------------+ | json_extract('[10, 20, [30, 40]]', '$[0]') | +-------------------------------------------+ | 10 | +-------------------------------------------+Return the value of the path `$date` from
{"id":"1","$date":"12345"}. The statement is as follows:SELECT JSON_EXTRACT('{"id":"1","$date":"12345"}', '$["$date"]');The following result is returned:
+---------------------------------------------------------+ |JSON_EXTRACT('{"id":"1","$date":"12345"}', '$["$date"]') | +---------------------------------------------------------+ | "12345" | +---------------------------------------------------------+
JSON_KEYS
json_keys(json[, json_path])Description
If
json_pathis specified, this function returns all keys from the specified path of the JSON document.If
json_pathis not specified, this function returns all keys from the root path (json_path='$').
Input value type: Only parameters of the JSON type are supported.
You can construct JSON data in the following ways:
Use JSON data directly. For example,
json '{"a": 1, "b": {"c": 30}}'.Explicitly cast a string to JSON data using the CAST function. For example,
CAST('{"a": 1, "b": {"c": 30}}' AS json).
Return value type: JSON ARRAY.
Examples:
Return all keys from the path
$.b. The statement is as follows:SELECT json_keys(CAST('{"a": 1, "b": {"c": 30}}' AS json),'$.b');The following result is returned:
+-----------------------------------------------------------+ | json_keys(CAST('{"a": 1, "b": {"c": 30}}' AS json),'$.b') | +-----------------------------------------------------------+ | ["c"] | +-----------------------------------------------------------+Return all keys from the root path. The statement is as follows:
SELECT JSON_KEYS(json '{"a": 1, "b": {"c": 30}}');The following result is returned:
+--------------------------------------------+ | JSON_KEYS(json '{"a": 1, "b": {"c": 30}}') | +--------------------------------------------+ | ["a","b"] | +--------------------------------------------+
JSON_OVERLAPS
This syntax is supported only in clusters with a kernel version of 3.1.10.6 or later.
A JSON array index must be created for the specified JSON column. For more information, see Create a JSON array index.
You can add
EXPLAINbefore your SQL query statement to view the execution plan. If the execution plan does not contain the `ScanFilterProject` operator, the JSON array index was used successfully. Otherwise, the index was not used.
json_overlaps(json, cast('[candidate1,candidate2,candidate]' as json)) Description: Checks whether the specified JSON document contains any of the specified elements, such as
candidate1,candidate2, orcandidate3.Data types of the input values:
candidate1,candidate2,candidate3,...can be of the numeric type or string type, and all values must have the same data type.Return value type: VARCHAR.
Examples:
Return data from the specified JSON column
vjthat containsCP-018673.SELECT * FROM json_test WHERE json_overlaps(vj, cast('["CP-018673"]' AS json));The following result is returned:
+-----+----------------------------------------------------------------------------+ | id | vj | +-----+----------------------------------------------------------------------------+ | 2 | ["CP-018673", 1, false] | +-----+----------------------------------------------------------------------------+ | 3 | ["CP-018673", 1, false, {"a": 1}] | +-----+----------------------------------------------------------------------------+ | 5 | ["CP-018673","CP-018671","CP-018672","CP-018670","CP-018669","CP-018668"] | +-----+----------------------------------------------------------------------------+Return data from the specified JSON column
vjthat contains any of the elements1,2, or3.SELECT * FROM json_test WHERE json_overlaps(vj, cast('[1,2,3]' AS json))The following result is returned:
+-----+-------------------------------------+ | id | vj | +-----+-------------------------------------+ | 1 | [1,2,3] | +-----+-------------------------------------+ | 2 | ["CP-018673", 1, false] | +-----+-------------------------------------+ | 3 | ["CP-018673", 1, false, {"a": 1}] | +-----+-------------------------------------+
JSON_REMOVE
The `JSON_REMOVE` function is supported only in clusters with a kernel version of 3.1.10.0 or later.
To view and update the minor version, go to the Configuration Information section on the Cluster Information page in the AnalyticDB for MySQL console.
json_remove(json,json_path)
json_remove(json,array[json_path,json_path,...])Description: Removes the element at the specified
json_pathfrom ajsondocument and returns the modified string. You can specify multiple elements to remove using `array[json_path,json_path,...]`.Input value type:
jsonis a VARCHAR string in JSON format.json_pathis a VARCHAR string in JSON format.Return value type: VARCHAR.
Examples
Remove the element at the path
$.glossary.GlossDivand return the modified string. The statement is as follows:SELECT json_remove( '{ "glossary": { "title": "example glossary", "GlossDiv": { "title": "S", "GlossList": { "GlossEntry": { "ID": "SGML", "SortAs": "SGML", "GlossTerm": "Standard Generalized Markup Language", "Acronym": "SGML", "Abbrev": "ISO 8879:1986", "GlossDef": { "para": "A meta-markup language, used to create markup languages such as DocBook.", "GlossSeeAlso": ["GML", "XML"] }, "GlossSee": "markup" } } } } }' , '$.glossary.GlossDiv') a;The following result is returned:
{"glossary":{"title":"example glossary"}}Remove the elements at the paths
$.glossary.titleand$.glossary.GlossDiv.titleand return the modified string. The statement is as follows:SELECT json_remove( '{ "glossary": { "title": "example glossary", "GlossDiv": { "title": "S", "GlossList": { "GlossEntry": { "ID": "SGML", "SortAs": "SGML", "GlossTerm": "Standard Generalized Markup Language", "Acronym": "SGML", "Abbrev": "ISO 8879:1986", "GlossDef": { "para": "A meta-markup language, used to create markup languages such as DocBook.", "GlossSeeAlso": ["GML", "XML"] }, "GlossSee": "markup" } } } } }' , array['$.glossary.title', '$.glossary.GlossDiv.title']) a;The following result is returned:
{"glossary":{"GlossDiv":{"GlossList":{"GlossEntry":{"GlossTerm":"Standard Generalized Markup Language","GlossSee":"markup","SortAs":"SGML","GlossDef":{"para":"A meta-markup language, used to create markup languages such as DocBook.","GlossSeeAlso":["GML","XML"]},"ID":"SGML","Acronym":"SGML","Abbrev":"ISO 8879:1986"}}}}}
JSON_SIZE
json_size(json, json_path)Description: Returns the size of a JSON object or array at the specified
json_path.NoteIf
json_pathdoes not point to a JSON object or array, this function returns `0`.Input value type: String or JSON.
Return value type: BIGINT.
Examples:
json_pathpoints to a JSON object. The statement is as follows:SELECT json_size('{"x":{"a":1, "b": 2}}', '$.x') as result;The following result is returned:
+--------+ | result | +--------+ | 2 | +--------+json_pathdoes not point to a JSON object or array. The statement is as follows:SELECT json_size('{"x": {"a": 1, "b": 2}}', '$.x.a') as result;The following result is returned:
+--------+ | result | +--------+ | 0 | +--------+
JSON_SET
The `JSON_SET` function is supported only in clusters with a kernel version of 3.2.2.8 or later.
To view and update the minor version, go to the Configuration Information section on the Cluster Information page in the AnalyticDB for MySQL console.
json_set(json, json_path, value[, json_path, value] ...)Description: Inserts or updates data in a
jsondocument at the specifiedjson_pathand returns the updatedjsondocument.If
jsonorjson_pathis null, the function returns null.If the
jsondocument is not in a valid JSON format, or if anyjson_pathis not a valid path expression, an exception is thrown.If the specified
json_pathexists, its value is overwritten withvalue.If the specified
json_pathdoes not exist in thejsondocument:If
json_pathpoints to a JSON object,valueis added as a new element at the location specified byjson_path.If
json_pathpoints to a JSON array, this function checks whether data exists at the position before the specifiedjson_path. If no data exists, `null` values are added to fill the gap beforevalueis inserted. Otherwise,valueis inserted directly.In other cases, an exception is thrown.
Input value types:
json: VARCHAR or JSON.json_path: VARCHAR.value: BOOLEAN, TINYINT, SMALLINT, INT, BIGINT, FLOAT, DOUBLE, DECIMAL, VARCHAR, VARBINARY, DATE, DATETIME, TIMESTAMP, or TIME.
Return value type: JSON.
Examples:
Insert data into a
jsondocument wherejson_pathis null.SELECT JSON_SET('{ "a": 1, "b": [2, 3]}', null, '10');Result:
+------------------------------------------------+ | JSON_SET('{ "a": 1, "b": [2, 3]}', NULL, '10') | +------------------------------------------------+ | null | +------------------------------------------------+Insert data into a
jsondocument wherejson_pathis not a valid path expression.SELECT JSON_SET('{ "a": 1, "b": [2, 3]}', '$.b.c', '10');Result:
Failed to execute json_set() for json_path: $.b.cInsert data into a
jsondocument wherejson_path1exists, andjson_path2does not exist and points to a JSON object.SELECT JSON_SET('{ "a": 1, "b": [2, 3]}', '$.a', 10, '$.c', '[true, false]');Result:
+-----------------------------------------------------------------------+ | JSON_SET('{ "a": 1, "b": [2, 3]}', '$.a', 10, '$.c', '[true, false]') | +-----------------------------------------------------------------------+ | {"a":10,"b":[2,3],"c":"[true, false]"} | +-----------------------------------------------------------------------+Insert data into a
jsondocument where the specifiedjson_pathdoes not exist and points to a JSON array.SELECT JSON_SET('{ "a": 1, "b": [2, 3]}', '$.b[4]', '[true, false]');Result:
+----------------------------------------------------------------+ | JSON_SET('{ "a": 1, "b": [2, 3]}', '$.b[4]', '[true, false]') | +----------------------------------------------------------------+ | {"a":1,"b":[2,3,null,null,"[true, false]"]} | +----------------------------------------------------------------+
JSON_UNQUOTE
json_unquote(json_value)This function is supported only in clusters with a kernel version of 3.1.5.0 or later.
To view and update the minor version, go to the Configuration Information section on the Cluster Information page in the AnalyticDB for MySQL console.
This command removes double quotation marks from
json_value, escapes certain escape characters, and returns the resulting value.AnalyticDB for MySQL does not validate
json_value. This function processes the value based on the logic described, regardless of whetherjson_valueconforms to the JSON syntax.The supported escape characters are listed in the following table.
Before unescaping
After unescaping
\"Double quotation mark (
").\bBackspace.
\fForm feed.
\nLine feed.
\rCarriage return.
\tTab.
\\Backslash (
\).\uXXXXUTF-8 character representation.
Input value type: VARCHAR.
Return value type: VARCHAR.
Examples:
Return the unquoted string
abc. The statement is as follows:SELECT json_unquote('"abc"');The following result is returned:
+-----------------------+ | json_unquote('"abc"') | +-----------------------+ | abc | +-----------------------+The following statement returns the unquoted and parsed string:
SELECT json_unquote('"\\t\\u0032"');The result is as follows:
+------------------------------+ | json_unquote('"\\t\\u0032"') | +------------------------------+ | 2 | +------------------------------+
Appendix: JSON Path syntax
Usage
Use
$.keyName[.keyName]...to access a specified key in a JSON object.Use
$[nonNegativeInteger]to access the Nth element in a JSON array, where n is a non-negative integer.Use
$.keyName[.keyName]...[nonNegativeInteger]to access the Nth element of a JSON array that is nested in a JSON object, where n is a non-negative integer.
Notes
The JSON Path syntax in AnalyticDB for MySQL does not support the * and ** wildcard characters. This means that expressions such as '$.*', '$.hobbies[*]', '$.address.**', and '$.hobbies.**' are not supported.
Examples
Assume that you have the following JSON data.
{
"name": "Alice",
"age": 25,
"address": {
"city": "Hangzhou",
"zip": "10001"
},
"hobbies":["reading", "swimming", "cycling"]
}Description | Correct example | Incorrect example |
Access the value of the key `name` | $.name | name |
Access the value of the key `city` in a nested object | $.address.city | $.address[0] |
Access the first element of the JSON array `hobbies` | $.hobbies[0] | $.hobbies.[0] |
FAQ
How do I resolve the java.lang.NullPointerException error when I use the JSON_OVERLAPS function?
Cause: This error occurs if you use an `ALTER` statement to create a JSON index, but the `BUILD` operation has not been executed or is not yet complete. In this case, the JSON index is not active.
Solution:
If the `BUILD` operation has not been executed:
An AnalyticDB for MySQL cluster automatically triggers a `BUILD` task when certain conditions are met. You can also manually trigger a `BUILD` task.
If the `BUILD` operation has been executed:
You can run the following statement to query the status of the `BUILD` task. If the
statusfield in the returned result isFINISH, the `BUILD` operation is complete.SELECT table_name, schema_name, status FROM INFORMATION_SCHEMA.KEPLER_META_BUILD_TASK ORDER BY create_time DESC LIMIT 10;
For more information about `BUILD`, see BUILD.
References
JSON: Describes the JSON data type.
JSON indexes: Describes how to create indexes for JSON objects and arrays.