How is json_contains used in MySQL?

The JSON_CONTAINS function in MySQL is used to determine if a JSON array contains a specified value. The syntax of the function is as follows:

JSON_CONTAINS(json_doc, value[, path])

json_doc: JSON value to be checked. value: value to be searched for. path: optional parameter, specifying the path to search within the JSON document. If not provided, the search will be conducted throughout the entire JSON document. The function returns a boolean value indicating whether a matching value was found. Here is an example: 1. Checking if a JSON array contains a specified value.

SELECT JSON_CONTAINS('[1, 2, 3]', 2);

The result is 1, indicating that the array contains the value 2. 2. Check if a JSON object contains a specified value at a given path:

SELECT JSON_CONTAINS('{"name": "John", "age": 30}', 'John', '$.name');

The result is 1, indicating that the value John was found at the $.name path. Check if a JSON object contains a specified value in the entire JSON document.

SELECT JSON_CONTAINS('{"name": "John", "age": 30}', 30);

The result is 1, indicating that the value 30 was found in the entire JSON document. Note that the JSON_CONTAINS function is available in MySQL 5.7 and above versions. If you are using an earlier version, you can achieve similar functionality using the JSON_CONTAINS_PATH function.

bannerAds