Recommended document: mysql official website -- JSON function
Mysql has introduced the json data type since 5.7. Compared with blob storing binary characters and text storing text type data, the data stored in json will verify whether it conforms to the json format. And the maximum text length that json can store is the same as the text length of longBlob and longText.
type of data | storage length |
TINYBLOB、TINYTEXT |
|
BLOB、TEXT |
|
MEDIUMBLOB、MEDIUMTEXT |
|
LONGBLOB 、LONGTEXT、 JSON |
|
JSON processing function in mysql:
function | describe |
---|---|
-> | Returns the value from the JSON column after evaluating the path; equivalent to JSON_EXTRACT(). |
->> | Returns the value from the JSON column after evaluating the path and dereferencing the result; equivalent to JSON_UNQUOTE(JSON_EXTRACT()). |
JSON_ARRAY() | Create JSON array |
JSON_ARRAY_APPEND() | Append data to JSON document |
JSON_ARRAY_INSERT() | Insert JSON array |
JSON_CONTAINS() | Whether the JSON document contains the specific object at the path |
JSON_CONTAINS_PATH() | Does the JSON document contain any data in the path |
JSON_DEPTH() | Maximum depth of JSON documents |
JSON_EXTRACT() | Return data from a JSON document |
JSON_INSERT() | Insert data into JSON document |
JSON_KEYS() | An array of keys from the JSON document |
JSON_LENGTH() | The number of elements in the JSON document |
JSON_MERGE() | Merge JSON documents, preserving duplicate keys. Deprecated JSON_MERGE_PRESERVE() synonym (deprecated) |
JSON_MERGE_PATCH() | Merge JSON documents, replacing values for duplicate keys |
JSON_MERGE_PRESERVE() | Merge JSON documents, preserving duplicate keys |
JSON_OBJECT() | Create JSON object |
JSON_OVERLAPS() | (Version 8.0.17) Compares two JSON documents and returns TRUE (1) if they have any key-value pairs or array elements in common, FALSE (0) otherwise |
JSON_PRETTY() | Print JSON documents in human readable format |
JSON_QUOTE() | Quoting a JSON document |
JSON_REMOVE() | Remove data from JSON document |
JSON_REPLACE() | Replace values in JSON documents |
JSON_SCHEMA_VALID() | (Version 8.0.17) Validates a JSON document against a JSON schema; returns 1 if the document validates against the schema, 0 otherwise |
JSON_SCHEMA_VALIDATION_REPORT() | (Version 8.0.17) Validates JSON documents against JSON Schema; returns a report on validation results in JSON format, including success or failure and the reason for failure |
JSON_SEARCH() | Value paths in JSON documents |
JSON_SET() | Insert data into JSON document |
JSON_STORAGE_FREE() | Space freed in binary representation of JSON column value after partial update |
JSON_STORAGE_SIZE() | space for storing the binary representation of the JSON document |
JSON_TABLE() | Return data in a JSON expression as a relational table |
JSON_TYPE() | Types of JSON values |
JSON_UNQUOTE() | dereference JSON value |
JSON_VALID() | Is the JSON value valid |
JSON_VALUE() | (Version 8.0.21) Extracts the value from the JSON document at the location pointed to by the provided path; returns this value as VARCHAR(512) or the specified type |
MEMBER OF() | (Version 8.0.17) Returns 1 if the first operand matches any element of the JSON array passed as the second operand, otherwise returns 0 |
Commonly used functions are introduced:
Create a table and insert data:
CREATE TABLE `zsm_json` (
`json_test` json DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin
INSERT INTO `zsm_json`(`json_test`) VALUES ('[1,2,3,4]');
INSERT INTO `zsm_json`(`json_test`) VALUES ('{\"a\": 1, \"b\": 2, \"c\": [3, 4, 5]}');
实际应用中最常用的是前两个函数, 从json文本中获取制定值
1、 -> 、 ->> 获取json元素
1.1、 基础操作, 获取json元素: jsonColumn -> '$.keyName'
select json_test -> '$.a' from zsm_json
select json_test -> '$."a"' from zsm_json // a带双引号
select json_test -> '$[0]' from zsm_json // 取第一个值
select json_test -> '$[1]' from zsm_json // 取第二个值
result1:
result2:
result3:
result4:
从上面的结果可以得出结论:
- json列既可以存储json对象也可以存储json数组
- 获取json中特定key的值,可以使用 $.keyName , keyName加不加双引号都行
- 如果json列中存储的是JSON数组, 可以使用$[index] 获取特定索引下的值, 而json对象被认为是只有一个元素的数组
1.2、json对象中存在数组元素或数组元素中存在json对象, 获取下层元素
// 获取JSON对象中key为 ‘c’的JSON数组中下标为2的元素
select json_test -> '$.c[2]' from zsm_json;
select json_test -> '$[0].c[2]' from zsm_json;
两个的查询结果都一样:
1.3 ->> 处理特殊字符
先往数据库中插入一条数据
INSERT INTO `zsm_json`(`json_test`) VALUES ('{"mascot": "Our mascot is a dolphin named \\"Sakila\\"."}');
查询:
select json_test -> '$.mascot' from zsm_json;
select json_test ->> '$.mascot' from zsm_json;
result1:
result2:
可以看到使用 -> 查询到的数据, 对于转义字符 \" 并没有进行转义; 而使用 ->> 查询的结果, 转义字符被转成正常的字符。
-> 的使用不限于select, 也可以用于where 、 update等操作中
2、JSON_EXTRACT 获取json数据
json_extract 的功能与 -> 相似,从json文本中获取数据。 他的语法格式:
JSON_EXTRACT(json_doc, path[, path] ...)
他可以一次获取多个value值, 并存放到一个数组中
SELECT JSON_EXTRACT('[10, 20, [30, 40]]', '$[1]', '$[0]');
SELECT JSON_EXTRACT('[10, 20, [30, 40]]', '$[2][*]');
具体的执行结果,这里就不再展示了。
3、其它搜索json值函数
- JSON_CONTAINS(target, candidate[, path]) : 判断candidate文档中是否包含target文档, 如果制定了path参数,则在 candidate 的 path 路径中寻找 target。 这里path不能使用通配符。
- JSON_CONTAINS_PATH(json_doc, one / all, path[, path] ...) : 判断json文档中是否包含制定路径。
-
'one'
: 如果文档中至少存在一个路径,则为 1,否则为 0。 -
'all'
: 如果文档中存在所有路径,则为 1,否则为 0。
-
-
JSON_KEYS(json_doc[, path]) : 返回json文档中的所有一级key, 如果path指定, 返回指定路径下的一级key
-
JSON_OVERLAPS(json_doc1, json_doc2) : 比较两个 JSON 文档是否具有任何共同的键值对或数组元素。
-
value MEMBER OF(json_array) : json数组中是否包含value值
-
JSON_SEARCH(json_doc, one / all, search_str[, escape_char[, path] ...]) : 返回json文档中给定字符串的路径。
-
'one'
:搜索在第一次匹配后终止并返回一个路径字符串。未定义首先考虑哪个匹配。当我们要匹配的值有多个, 返回第一个匹配到的value的key。 -
'all'
:搜索返回所有匹配的路径字符串,这样就不会包含重复的路径。如果有多个字符串,它们会自动包装为一个数组。数组元素的顺序未定义。 -
// 下面是mysql官方文档给出的示例语句 SET @j = '["abc", [{"k": "10"}, "def"], {"x":"abc"}, {"y":"bcd"}]'; SELECT JSON_SEARCH(@j, 'one', 'abc'); SELECT JSON_SEARCH(@j, 'all', 'abc'); SELECT JSON_SEARCH(@j, 'all', 'ghi');
-
-
JSON_VALUE(json_doc, path) : 从json文档中获取指定路径下的值。完整的语法格式如下:
JSON_VALUE(json_doc, path [RETURNING type] [on_empty] [on_error]) -- RETURNING type 用于制定返回值类型, -- type 取值 : float/double/decimal/signed/unsigned/date/char/json.... 如果不指定, 默认为 varchar(512) -- on_empty 未找到数据时,操作行为: -- NULL ON EMPTY : 默认行为 -- DEFAULT 'value' ON EMPTY : 返回value, 注意类型匹配 -- ERROR ON EMPTY : 抛出错误 -- on_error 发生错误时, 操作行为 -- NULL ON ERROR: 返回null, 默认行为 -- DEFAULT 'value' ON ERROR : 返回value, 注意类型匹配 -- ERROR ON ERROR : 抛出错误
4、修改JSON值得函数
- JSON_ARRAY_APPEND(json_doc, path, val[, path, val] ...) : 将值添加到json文档中指定数组的末尾并返回结果。
- JSON_ARRAY_INSERT(json_doc, path, val[, path, val] ...) : 在JSON文档的指定位置插入指定值。
- JSON_INSERT(json_doc, path, val[, path, val] ...) : 在json文档的指定路径上插入值,并返回整个json串
- JSON_MERGE_PATCH(json_doc, json_doc[, json_doc] ...): 合并多个json对象( json对象不是json数组)。 当多个json文档中存在相同的key时, 后面的key值会覆盖前面的json中的key值。
- 如果第一个参数不是json对象, 则会返回第二个参数, 无论第二个参数是否是json文档。
- 如果第二个参数不是json对象, 第一个参数是json对象, 返回第一个json对象
- JSON_MERGE_PRESERVE(json_doc, json_doc[, json_doc] ...) : 合并多个json对象, 不同的是它不会将值覆盖。
- 可以合并json数组
- 如果多个json对象中有相同的key, 这里不是覆盖,而是合并多个json对象中的key值
- JSON_REMOVE(json_doc, path[, path] ...) : 删除json文档中的指定值, 返回删除后的json串
- JSON_REPLACE(json_doc, path, val[, path, val] ...) : 替换json文档中的值
- JSON_SET(json_doc, path, val[, path, val] ...) : 设置JSON文档中的值
-
JSON_SET() 替换现有值并添加不存在的值。
-
JSON_INSERT() 插入值而不替换现有值。
-
JSON_REPLACE()仅替换 现有值。
-
5、JSON 属性函数:
- JSON_DEPTH(json_doc) : 返回json最大深度
- JSON_LENGTH(json_doc[, path]) : 返回json文档长度-- json数组长度, JSON对象key个数
- JSON_TYPE(json_val) : 返回
utf8mb4
指示 JSON 值类型的字符串。这可以是对象、数组或标量类型 - JSON_VALID(val) : 返回0 或 1 以指示是否为有效json串
6、JSON其它函数
- JSON_PRETTY(json_val) : 格式化json文档
- JSON_STORAGE_FREE(json_val) : How much storage space is left for the json column
- JSON_STORAGE_SIZE(json_val) : the number of bytes to store the json document