This topic describes the JSON functions that are supported by AnalyticDB for MySQL clusters.
JSON_ARRAY_CONTAINS: checks whether a JSON array contains the value specified by the
valueparameter.JSON_ARRAY_LENGTH: returns the length of a JSON array.
JSON_CONTAINS (Version 3.1.5.0 or later): checks whether the specified path contains the value of
candidate. If a path is not specified, this function checks whether the target contains the value specified bycandidate.JSON_CONTAINS_PATH (Version 3.1.5.0 or later): checks whether a JSON document contains one or all of the specified paths.
JSON_EXTRACT: returns the value specified by the
json_pathparameter from a JSON document.JSON_KEYS: returns all keys of a JSON object at the path specified by
json_path. Ifjson_pathis not specified, this function returns all keys in the root path (json_path='$').JSON_OVERLAPS (Version 3.1.10.6 or later): checks whether a JSON document contains any of the specified candidate elements, such as
candidate1,candidate2, orcandidate3.JSON_REMOVE (Version 3.1.10.0 or later): removes the element specified by
json_pathfrom ajsondocument and returns the new string. You can specify multiple paths in an array to remove multiple elements.JSON_SIZE: returns the size of the JSON object or array specified by the
json_pathparameter.JSON_SET (Versions 3.2.2.8 and later): inserts or updates data in a
jsondocument at the specifiedjson_pathand returns the updatedjsondocument.JSON_UNQUOTE (Version 3.1.5.0 or later): removes the double quotes from
json_value, unescapes specified escape characters injson_value, and returns the result.
JSON_ARRAY_CONTAINS
json_array_contains(json, value)Description: Checks whether a JSON array contains the specified
value.Input value type: The
valueparameter can be a numeric, string, or BOOLEAN type.Return value type: BOOLEAN.
Example:
Checks whether the JSON array
[1, 2, 3]contains an element with the value 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:
Returns 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 JSON document contains specific content. You can use JSON array indexes in queries to avoid full table scans or parsing the entire JSON document. This improves query performance.
Without a JSON index
This syntax is supported only by AnalyticDB for MySQL clusters of version 3.1.5.0 or later.
To view and update the minor version of an AnalyticDB for MySQL cluster, log on to the AnalyticDB for MySQL console and go to the Configuration Information section of the Cluster Information page.
json_contains(target, candidate[, json_path])Description:
If
json_pathis specified, this function checks whether the path contains thecandidatevalue. It returns 1 for true and 0 for false.If
json_pathis not specified, this function checks whether the target document contains thecandidatevalue. It returns 1 for true and 0 for false.
The following rules apply:
If
targetandcandidateare both primitive types, such as NUMBER, BOOLEAN, STRING, or NULL, `target` contains `candidate` if they are equal.If
targetandcandidateare both JSON arrays, `target` contains `candidate` if every element in `candidate` is also an element of `target`.If
targetis an array andcandidateis not, `target` contains `candidate` if `candidate` is an element of `target`.If
targetandcandidateare both JSON objects, `target` contains `candidate` if every key in `candidate` also exists in `target`, and the value for each key in `candidate` is contained within the corresponding value in `target`.
Input value types: The
targetandcandidateparameters are of the JSON type. Thejson_pathparameter is of the JSONPATH type.Return value type: BOOLEAN.
Examples:
Checks 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 | +--------+Checks 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 | +--------+Checks 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 by AnalyticDB for MySQL clusters of version 3.1.10.6 or later.
Create a JSON array index for the specified JSON column. For more information, see Create a JSON array index.
You can add
EXPLAINbefore an SQL statement to view its execution plan. If the execution plan does not include the ScanFilterProject operator, the JSON array index was successfully used for the query. Otherwise, the JSON array index was not used.
json_contains(json_path, cast('[candidate1,candidate2,candidate3]' as json)) Description: Checks whether a JSON document contains all specified elements, such as
candidate1,candidate2, andcandidate3.Input value types: The values for
candidate1, candidate2, candidate3, ...can be numeric or string, and must all be of the same data type.Return value type: VARCHAR.
Examples:
Checks 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 | +------------------------------------------------------------+Checks 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 by AnalyticDB for MySQL clusters of version 3.1.5.0 or later.
To view and update the minor version of an AnalyticDB for MySQL cluster, log on to the AnalyticDB for MySQL console and go to the Configuration Information section of the Cluster Information page.
Description: Checks whether a JSON document contains a value at a specified path.
If
one_or_allis set to'one', this function returns 1 if the JSON document contains at least one of the specified paths. Otherwise, it returns 0.If
one_or_allis set to'all', this function returns 1 if the JSON document contains all of the specified paths. Otherwise, it returns 0.
Input value types: The
jsonparameter is of the JSON type. Theone_or_allparameter is of the VARCHAR type. Valid values are'one'or'all', which are case-insensitive. Thejson_pathparameter is a path.Return value type: BOOLEAN.
Examples:
Checks whether a 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 | +--------+Checks whether a JSON document contains both the
$.aand$.epaths. 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 values of the JSON_EXTRACT function do not support
ORDER BY, which is similar to columns of the JSON type.When you use 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 before you use it as an input parameter for the JSON_UNQUOTE function.
json_extract(json, json_path)Description: Returns the value specified by
json_pathfrom a JSON document. If a key injsoncontains special characters, such as$or., the format ofjson_pathmust be'$["Key"]'.For example, if the key is
$data, specify the `json_path` as'$["$data"]'.Input value type: STRING or JSON.
Return value type: JSON.
Examples:
Returns 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 | +-------------------------------------------+Returns the value of the `$date` path 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 JSON object at that path.If
json_pathis not specified, this function returns all keys from the root object, which is equivalent tojson_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. Example:
json '{"a": 1, "b": {"c": 30}}'.Use the CAST function to explicitly convert a string to JSON data. Example:
CAST('{"a": 1, "b": {"c": 30}}' AS json).
Return value type: JSON array.
Examples:
Returns all keys in the
$.bpath. 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"] | +-----------------------------------------------------------+Returns all keys in 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 by AnalyticDB for MySQL clusters of version 3.1.10.6 or later.
Create a JSON array index for the specified JSON column. For more information, see Create a JSON array index.
You can add
EXPLAINbefore an SQL statement to view its execution plan. If the execution plan does not include the ScanFilterProject operator, the JSON array index was successfully used for the query. Otherwise, the JSON array index was not used.
json_overlaps(json, cast('[candidate1,candidate2,candidate]' as json)) Description: Checks whether a JSON document contains any of the specified elements, such as
candidate1,candidate2, andcandidate3.Input value types: The
candidate1, candidate2, candidate3, ...parameters accept numeric or string values. All values must be of the same data type.Return value type: VARCHAR.
Examples:
Returns data that contains
CP-018673from the specified JSON columnvj.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"] | +-----+----------------------------------------------------------------------------+Returns data that contains any of the elements
1,2, or3from the specified JSON columnvj.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 by AnalyticDB for MySQL clusters of version 3.1.10.0 or later.
To view and update the minor version of an AnalyticDB for MySQL cluster, log on to the AnalyticDB for MySQL console and go to the Configuration Information section of the Cluster Information page.
json_remove(json,json_path)
json_remove(json,array[json_path,json_path,...])Description: Removes one or more elements specified by
json_pathfrom ajsondocument and returns the new string. You can specify multiple paths in an array, such as `array[json_path, json_path, ...]` to remove multiple elements.Input value types: The
jsonparameter is a VARCHAR string in JSON format. Thejson_pathparameter is a VARCHAR string in JSON format.Return value type: VARCHAR.
Examples
Removes the part at the path
$.glossary.GlossDivand returns 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"}}Removes the parts at the paths
$.glossary.titleand$.glossary.GlossDiv.titleand returns 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 the JSON object or JSON array that is specified by
json_path.NoteThis function returns 0 if
json_pathdoes not point to a JSON object or a JSON array.Input value type: STRING or JSON.
Return value type: BIGINT.
Examples:
The
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 | +--------+The
json_pathdoes not point to a JSON object or a JSON 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 by AnalyticDB for MySQL clusters of version 3.2.2.8 or later.
To view and update the minor version of an AnalyticDB for MySQL cluster, log on to the AnalyticDB for MySQL console and go to the Configuration Information section of the Cluster Information page.
json_set(json, json_path, value[, json_path, value] ...)Description: Inserts or updates data in a
jsondocument at a specifiedjson_pathand returns the updatedjsondocument.If the
jsonorjson_pathparameter is null, this function returns null.An exception is thrown if
jsonis not a valid JSON document, or if anyjson_pathis not a valid path expression.If the specified
json_pathexists, its value is overwritten by the newvalue.If the specified
json_pathdoes not exist injson:If
json_pathpoints to a JSON object, thevalueis added as a new element to the location specified byjson_path.If
json_pathpoints to a JSON array, this function checks whether there are empty slots before the position specified byjson_path. If empty slots exist, they are filled with `null` values before thevalueis inserted. Otherwise, thevalueis inserted directly.An exception is thrown in other cases.
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:
Inserts 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 | +------------------------------------------------+Inserts 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.cInserts data into a
jsondocument. The pathjson_path1exists, butjson_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]"} | +-----------------------------------------------------------------------+Inserts data into a
jsondocument. 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 by AnalyticDB for MySQL clusters of version 3.1.5.0 or later.
To view and update the minor version of an AnalyticDB for MySQL cluster, log on to the AnalyticDB for MySQL console and go to the Configuration Information section of the Cluster Information page.
Description: Unquotes
json_valueby removing the outer double quotes and unescaping specific characters within the value, and then returns the result.AnalyticDB for MySQL does not validate the
json_valueparameter. Thejson_valueparameter is processed based on the preceding logic, regardless of whether the parameter conforms to the JSON syntax.The following table describes the supported escape characters.
Before escaping
After escaping
\"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:
Returns the unquoted string
abc. The statement is as follows:SELECT json_unquote('"abc"');The following result is returned:
+-----------------------+ | json_unquote('"abc"') | +-----------------------+ | abc | +-----------------------+Returns the unquoted and parsed string. The statement is as follows:
SELECT json_unquote('"\\t\\u0032"');The following result is returned:
+------------------------------+ | 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 n-th element of a JSON array, where n is a non-negative integer.Use
$.keyName[.keyName]...[nonNegativeInteger]to access the n-th element of a nested JSON array in a JSON object, where n is a non-negative integer.
Notes
The JSON Path syntax in AnalyticDB for MySQL does not support the wildcard characters * and **. For example, the expressions '$.*', '$.hobbies[*]', '$.address.**', and '$.hobbies.**' are not supported.
Example
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 name key | $.name | name |
Access the value of the city key in the nested object | $.address.city | $.address[0] |
Access the first element of the hobbies JSON array | $.hobbies[0] | $.hobbies.[0] |
FAQ
How do I resolve the java.lang.NullPointerException error when using the JSON_OVERLAPS function?
Cause: This error occurs because a BUILD operation was not performed after you created a JSON index using the ALTER statement, or the BUILD operation is not complete. In this case, the JSON index has not taken effect.
Solution:
If a BUILD task was not performed:
AnalyticDB for MySQL clusters automatically trigger a BUILD task after specific conditions are met. You can also manually trigger a BUILD task.
If a BUILD task was performed:
Execute the following statement to query the status of the BUILD task. If the value of the
statusfield 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: learn about the JSON type.
JSON indexes: learn how to create indexes for JSON objects or JSON arrays.